<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>JSP/Servlet及相关技术笔记 | 净土</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="JSP/Servlet及相关技术笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="JSP/Servlet及相关技术笔记">
<meta property="og:url" content="http://howiefh.github.io/2015/03/13/jsp-servlet-note/index.html">
<meta property="og:site_name" content="净土">
<meta property="og:description" content="JSP/Servlet及相关技术笔记">
<meta property="og:updated_time" content="2015-04-12T12:00:43.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JSP/Servlet及相关技术笔记">
<meta name="twitter:description" content="JSP/Servlet及相关技术笔记">
  
    <link rel="alternative" href="/atom.xml" title="净土" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.ico">
  
  <link href="http://fonts.useso.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="/css/style.css" type="text/css">
  
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-40492061-1', 'auto');
ga('send', 'pageview');

</script>


  
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?56d2899c5e919fbf4a7b00de5d1c31dd";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>


</head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">净土</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/" id="subtitle">乐不在外而在心，心以为乐，则是境皆乐；心以为苦，则无境不苦。</a>
        </h2>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-github-link" class="nav-icon" href="https://github.com/howiefh" title="Github" target="_blank"></a>
        
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed" target="_blank"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://howiefh.github.io"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-jsp-servlet-note" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    
<a href="/2015/03/13/jsp-servlet-note/" class="article-date">
  <time datetime="2015-03-13T02:04:54.000Z" itemprop="datePublished">2015-03-13</time>
</a>


    
  <div class="article-category">
    <a class="article-category-link" href="/categories/JavaEE/">JavaEE</a>►<a class="article-category-link" href="/categories/JavaEE/JSP/">JSP</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      JSP/Servlet及相关技术笔记
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
		
		<div id="toc" class="toc-article">
			<h2 class="toc-title"><span>Contents</span></h2>
		
			<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#web应用"><span class="toc-number">1.</span> <span class="toc-text">web应用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#java脚本"><span class="toc-number">2.</span> <span class="toc-text">java脚本</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jsp注释"><span class="toc-number">3.</span> <span class="toc-text">jsp注释</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jsp声明"><span class="toc-number">4.</span> <span class="toc-text">jsp声明</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#输出jsp表达式"><span class="toc-number">5.</span> <span class="toc-text">输出jsp表达式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jsp_3个编译指令"><span class="toc-number">6.</span> <span class="toc-text">jsp 3个编译指令</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#page指令"><span class="toc-number">6.1.</span> <span class="toc-text">page指令</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#include指令"><span class="toc-number">6.2.</span> <span class="toc-text">include指令</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jsp7个动作指令"><span class="toc-number">7.</span> <span class="toc-text">jsp7个动作指令</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#forward指令"><span class="toc-number">7.1.</span> <span class="toc-text">forward指令</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#include指令-1"><span class="toc-number">7.2.</span> <span class="toc-text">include指令</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#useBean、setProperty、getProperty指令"><span class="toc-number">7.3.</span> <span class="toc-text">useBean、setProperty、getProperty指令</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#param指令"><span class="toc-number">7.4.</span> <span class="toc-text">param指令</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jsp脚本中的9个内置对象"><span class="toc-number">8.</span> <span class="toc-text">jsp脚本中的9个内置对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#application"><span class="toc-number">8.1.</span> <span class="toc-text">application</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#config"><span class="toc-number">8.2.</span> <span class="toc-text">config</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#exception"><span class="toc-number">8.3.</span> <span class="toc-text">exception</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#out"><span class="toc-number">8.4.</span> <span class="toc-text">out</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#pageContext"><span class="toc-number">8.5.</span> <span class="toc-text">pageContext</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#request"><span class="toc-number">8.6.</span> <span class="toc-text">request</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#response"><span class="toc-number">8.7.</span> <span class="toc-text">response</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#session"><span class="toc-number">8.8.</span> <span class="toc-text">session</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#servlet介绍"><span class="toc-number">9.</span> <span class="toc-text">servlet介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Servlet的开发"><span class="toc-number">9.1.</span> <span class="toc-text">Servlet的开发</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#servlet的配置"><span class="toc-number">9.2.</span> <span class="toc-text">servlet的配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#JSP/Servlet的生命周期"><span class="toc-number">9.3.</span> <span class="toc-text">JSP/Servlet的生命周期</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#load-on-startup_Servlet"><span class="toc-number">9.4.</span> <span class="toc-text">load-on-startup Servlet</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#访问Servlet的配置参数"><span class="toc-number">9.5.</span> <span class="toc-text">访问Servlet的配置参数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用Servlet作为控制器"><span class="toc-number">9.6.</span> <span class="toc-text">使用Servlet作为控制器</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JSP_2的自定义标签"><span class="toc-number">10.</span> <span class="toc-text">JSP 2的自定义标签</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#开发自定义标签类"><span class="toc-number">10.1.</span> <span class="toc-text">开发自定义标签类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#建立TLD文件"><span class="toc-number">10.2.</span> <span class="toc-text">建立TLD文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用标签库"><span class="toc-number">10.3.</span> <span class="toc-text">使用标签库</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#带属性的标签"><span class="toc-number">10.4.</span> <span class="toc-text">带属性的标签</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#带标签体的标签"><span class="toc-number">10.5.</span> <span class="toc-text">带标签体的标签</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#以页面片段作为属性的标签"><span class="toc-number">10.6.</span> <span class="toc-text">以页面片段作为属性的标签</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#动态属性的标签"><span class="toc-number">10.7.</span> <span class="toc-text">动态属性的标签</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Filter介绍"><span class="toc-number">11.</span> <span class="toc-text">Filter介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#创建Filter类"><span class="toc-number">11.1.</span> <span class="toc-text">创建Filter类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#配置Filter"><span class="toc-number">11.2.</span> <span class="toc-text">配置Filter</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Listener_介绍"><span class="toc-number">12.</span> <span class="toc-text">Listener 介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#实现Listenner类"><span class="toc-number">12.1.</span> <span class="toc-text">实现Listenner类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#配置Listener"><span class="toc-number">12.2.</span> <span class="toc-text">配置Listener</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用ServletRequestListener和ServletRequestAttributeListener"><span class="toc-number">12.3.</span> <span class="toc-text">使用ServletRequestListener和ServletRequestAttributeListener</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用HttpSessionListener和HttpSessionAttributeListener"><span class="toc-number">12.4.</span> <span class="toc-text">使用HttpSessionListener和HttpSessionAttributeListener</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JSP_2特性"><span class="toc-number">13.</span> <span class="toc-text">JSP 2特性</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#配置jsp属性"><span class="toc-number">13.1.</span> <span class="toc-text">配置jsp属性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#表达式语言"><span class="toc-number">13.2.</span> <span class="toc-text">表达式语言</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Tag_File_支持"><span class="toc-number">13.3.</span> <span class="toc-text">Tag File 支持</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Servlet_3-0新特性"><span class="toc-number">14.</span> <span class="toc-text">Servlet 3.0新特性</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Servlet_3-0的Annotation"><span class="toc-number">14.1.</span> <span class="toc-text">Servlet 3.0的Annotation</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Servlet_3-0的Web模块支持"><span class="toc-number">14.2.</span> <span class="toc-text">Servlet 3.0的Web模块支持</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Servlet_3-0提供的异步处理"><span class="toc-number">14.3.</span> <span class="toc-text">Servlet 3.0提供的异步处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#改进的Servlet_API"><span class="toc-number">14.4.</span> <span class="toc-text">改进的Servlet API</span></a></li></ol></li></ol>
		
		</div>
		
        <h2 id="web应用">web应用</h2><figure class="highlight gherkin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">`<span class="variable">&lt;webDemo&gt;</span>` : web应用名称</span><br><span class="line">|<span class="string">--WEB-INF</span><br><span class="line"></span>|<span class="string">   </span>|<span class="string">--classes : 保存单个`*.class`文件</span><br><span class="line"></span>|<span class="string">   </span>|<span class="string">--lib     : 保存jar包</span><br><span class="line"></span>|<span class="string">   </span>|<span class="string">--web.xml : 配置描述符，servlet3.0后不再是必须</span><br><span class="line"></span>|<span class="string">--`&lt;a.jsp&gt;` : jsp页面</span></span><br></pre></td></tr></table></figure>
<h2 id="java脚本">java脚本</h2><p><code>&lt;% %&gt;</code>中的内容即java脚本，会被系统编译在Servlet类中的service方法中。<br>每个jsp页面其实还是servlet</p>
<a id="more"></a>
<h2 id="jsp注释">jsp注释</h2><p><code>&lt;%-- 注释内容 --%&gt;</code>不会被输出到浏览器中</p>
<h2 id="jsp声明">jsp声明</h2><p><code>&lt;%! 声明部分 %&gt;</code>声明部分用于声明变量和方法。声明的变量和方法对应于编译后Servlet类中的成员变量和方法。</p>
<p>jsp页面会编译成Servlet类，每个Servlet在容器中只有一个实例：在jsp中声明的变量是成员变量，成员变量，成员变量只在创建实例时初始化，该变量的值将一直保存，直到实例销毁。</p>
<h2 id="输出jsp表达式">输出jsp表达式</h2><p><code>&lt;%= 表达式 %&gt;</code> 不可以有分号，编译时会转换为Servlet中的输出语句。</p>
<h2 id="jsp_3个编译指令">jsp 3个编译指令</h2><ul>
<li>page：该指令是针对当前页面的指令</li>
<li>include：用于指定包含另一个页面</li>
<li>taglib：用于定义和访问自定义标签</li>
</ul>
<p>编译指令的语法格式</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">%@</span> 编译指令名 属性名=<span class="value">"属性值"</span><span class="value">...</span> %&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="page指令">page指令</h3><ul>
<li>language：声明当前jsp页面使用的脚本语言种类，默认是java。</li>
<li>extends：指定jsp页面编译所产生的java类所继承的父类，或所实现的接口。</li>
<li>import：用于导入包，<code>java.lang.*、javax.servlet.*、javax.servlet.jsp.*、javax.servlet.http.*</code></li>
<li>session：设定这个jsp页面是否需要http session</li>
<li>buffer：指定输出缓存区大小，jsp内部对象：out用于缓存jsp页面对客户端浏览器的输出。默认值为8kb，可以设置为none，也可设为其它值，单位kb。</li>
<li>autoFlush：当缓存即将溢出时，是否需要强制输出缓存区的内容。设置为true时为正常输出；如果设置为false，则会在溢出时产生异常。</li>
<li>info：设置jsp程序的信息，可调用getServletInfo()方法获取该值，因为jsp页面实质就是Servlet。</li>
<li>errorPage：指定错误处理页面。如果本页面产生异常或错误，而该jsp页面没有对应处理代码，将会自动调用指定的页面。实质是jsp的异常处理机制，jsp脚本不要求强制处理异常，即使是受检查的。</li>
<li>isErrorPage：设置本jsp页面是否为错误处理程序，如果该页面已经是错误处理页面，则无需errorPage属性。</li>
<li>contentType：用于设定生成网页的文件格式和编码字符集，即MIME类型和页面字符集类型，默认MIME类型是text/html，默认的字符集类型为ISO-8859-1。</li>
<li>pageEncoding：指定生成网页的编码字符集。</li>
</ul>
<h3 id="include指令">include指令</h3><p>include指令会将包含的页面加入到本页面，融合成一个页面，因此被包含页面甚至不需要是一个完整的页面，可以是静态页面，也可以是动态的jsp页面。</p>
<p>语法</p>
<figure class="highlight mel"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;<span class="variable">%@</span>include <span class="keyword">file</span>=<span class="string">"relativeUrlSpec"</span><span class="variable">%&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>注意，静态include会将包含页面的编译指令也包含进来，如果两个页面的编译指令冲突，那么页面就会出错</strong>。</p>
<h2 id="jsp7个动作指令">jsp7个动作指令</h2><ul>
<li>jsp:forward：执行页面转向，将请求的处理转发到下一个页面。</li>
<li>jsp:param：用于传递参数，必须与其他支持参数的标签一起使用。</li>
<li>jsp:include：用于动态引入一个jsp页面。</li>
<li>jsp:plugin：用于下载JavaBean或Applet到客户端执行。很少会用到。</li>
<li>jsp:useBean：创建一个JavaBean实例。</li>
<li>jsp:setProperty：设置JavaBean实例的属性。</li>
<li>jsp:getProperty：获取JavaBean实例的属性。</li>
</ul>
<h3 id="forward指令">forward指令</h3><p>既可以转发到静态的html页面，也可以转发到动态的jsp页面，或者转发到容器中的Servlet。</p>
<p>jsp1.0：</p>
<figure class="highlight erb"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"><span class="tag">&lt;<span class="title">jsp:forward</span> <span class="attribute">page</span>=<span class="value">"&#123;relativeURL|</span></span></span>&lt;%=<span class="ruby">expression</span>%&gt;<span class="xml"><span class="tag"><span class="value">&#125;"</span>/&gt;</span></span></span><br></pre></td></tr></table></figure>
<p>jsp1.1</p>
<figure class="highlight erb"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"><span class="tag">&lt;<span class="title">jsp:forward</span> <span class="attribute">page</span>=<span class="value">"&#123;relativeURL|</span></span></span>&lt;%=<span class="ruby">expression</span>%&gt;<span class="xml"><span class="tag"><span class="value">&#125;"</span>&gt;</span></span><br><span class="line">&#123;<span class="tag">&lt;<span class="title">jsp:param</span> <span class="attribute">name</span>=<span class="value">"name"</span> <span class="attribute">value</span>=<span class="value">"value"</span>/&gt;</span>&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="title">jsp:forward</span>&gt;</span></span></span><br></pre></td></tr></table></figure>
<p>第二种用于转发时添加额外的请求参数。</p>
<p><strong>执行forward指令时，用户请求的地址依然没有发生改变，但页面内容却完全变为被forward目标页的内容</strong>。</p>
<p>执行forward指令时，客户端请求参数不会丢失。</p>
<p><strong>实际上forward并没有重新向新页面发送请求，它只是完全采用了新页面来对用户生成响应—请求依然是一次，所以请求参数、属性没丢失</strong>。</p>
<h3 id="include指令-1">include指令</h3><p><strong>动态include指令，也用于包含某个页面，它不会导入include页面的编译指令，仅仅将被导入页面的body内容插入本页面</strong>。</p>
<p>语法</p>
<figure class="highlight erb"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"><span class="tag">&lt;<span class="title">jsp:include</span> <span class="attribute">page</span>=<span class="value">"&#123;relativeURL|</span></span></span>&lt;%=<span class="ruby">expression</span>%&gt;<span class="xml"><span class="tag"><span class="value">&#125;"</span> <span class="attribute">flush</span>=<span class="value">"true"</span>/&gt;</span></span><br><span class="line">//或</span><br><span class="line"><span class="tag">&lt;<span class="title">jsp:include</span> <span class="attribute">page</span>=<span class="value">"&#123;relativeURL|</span></span></span>&lt;%=<span class="ruby">expression</span>%&gt;<span class="xml"><span class="tag"><span class="value">&#125;"</span> <span class="attribute">flush</span>=<span class="value">"true"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">jsp:param</span> <span class="attribute">name</span>=<span class="value">"name"</span> <span class="attribute">value</span>=<span class="value">"value"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">jsp:include</span>&gt;</span></span></span><br></pre></td></tr></table></figure>
<p>编译为servlet后，只是使用一个include方法来插入目标页面内容，而不是将目标页面完全融入本页面中。</p>
<p><strong>静态导入和动态导入的三点区别</strong>：</p>
<ul>
<li>静态导入是将导入页面的代码完全融入，两个页面融合成一个整体servlet；而动态导入则在servlet中使用include方法来引入被导入页面的内容。</li>
<li>静态导入时被导入页面的编译指令会起作用；而动态导入时被导入页面的编译指令则失去作用，只是插入被导入页面的body内容。</li>
<li>动态包含还可以增加额外的参数。</li>
</ul>
<p>forward 指令和 include 指令动作十分相似。forward 指令使用_jspx_page_context的forward() 方法来引入目标页面。include用JspRuntimeLibrary 的include()方法引入目标页面。区别在于：forward拿目标页面代替原有页面，而include则拿目标页面插入原有页面。</p>
<h3 id="useBean、setProperty、getProperty指令">useBean、setProperty、getProperty指令</h3><p>这三个指令都是与JavaBean相关的指令，其中useBean指令用于在JSP页面中初始化一个Java实例；setProperty指令用于为JavaBean实例的属性设置值；getProperty指令用于输出JavaBean实例的属性。</p>
<p>useBean语法格式如下：</p>
<figure class="highlight nix"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;jsp:useBean <span class="variable">id=</span><span class="string">"name"</span> <span class="variable">class=</span><span class="string">"classname"</span> <span class="variable">scope=</span><span class="string">"page|request|session|application"</span>/&gt;</span><br></pre></td></tr></table></figure>
<p>其中id是JavaBean的实例名，class属性确定JavaBean的实现类。Scope属性用于指定JavaBean实例的作用范围：</p>
<p>page：仅在该页面有效。<br>request：在本次请求有效。<br>session：在本次session内有效。<br>application：在本次应用内一直有效。</p>
<p>setProperty语法格式如下：</p>
<figure class="highlight nix"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;jsp:setProperty <span class="variable">property=</span><span class="string">"ProtertyName"</span> <span class="variable">name=</span><span class="string">"BeanName"</span> <span class="variable">value=</span><span class="string">"value"</span>/&gt;</span><br></pre></td></tr></table></figure>
<p>name属性是需要设定JavaBean的实例名；property属性确定需要设置的属性名；value属性则确定需要设置的属性值。</p>
<p>getProperty语法格式如下：</p>
<figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;jsp:getProperty <span class="keyword">property</span>=<span class="string">"ProtertyName"</span> <span class="property">name</span>=<span class="string">"BeanName"</span> /&gt;</span><br></pre></td></tr></table></figure>
<p>name属性确定需要输出的JavaBean的实例名，property属性确定需要输出的属性名。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">body</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 创建lee.Person 实例，该实例的名称是p1--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">jsp:useBean</span> <span class="attribute">id</span>=<span class="value">"p1"</span> <span class="attribute">class</span>=<span class="value">"Person"</span> <span class="attribute">scope</span>=<span class="value">"page"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">jsp:setProperty</span> <span class="attribute">name</span>=<span class="value">"p1"</span> <span class="attribute">property</span>=<span class="value">"name"</span> <span class="attribute">value</span>=<span class="value">"waw"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">jsp:setProperty</span> <span class="attribute">name</span>=<span class="value">"p1"</span> <span class="attribute">property</span>=<span class="value">"age"</span> <span class="attribute">value</span>=<span class="value">"29"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="title">jsp:getProperty</span> <span class="attribute">name</span>=<span class="value">"p1"</span> <span class="attribute">property</span>=<span class="value">"name"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">jsp:getProperty</span> <span class="attribute">name</span>=<span class="value">"p1"</span> <span class="attribute">property</span>=<span class="value">"age"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">body</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>不使用这三个标签，也可以通过jsp脚本完成相同功能。</p>
<h3 id="param指令">param指令</h3><p>和jsp:include、jsp:forward、jsp:plugin指令结合使用，语法：</p>
<figure class="highlight livecodeserver"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;jsp:<span class="built_in">param</span> name=<span class="string">"paramName"</span> <span class="built_in">value</span>=<span class="string">"paramValue"</span> /&gt;</span><br></pre></td></tr></table></figure>
<h2 id="jsp脚本中的9个内置对象">jsp脚本中的9个内置对象</h2><p>jsp页面对应的Servlet的<code>_jspService()</code>方法来创建内置对象。</p>
<ul>
<li>application：javax.servlet.ServletContext的实例，<strong>该实例代表JSP所属的Web应用本身，可用于JSP页面，或者Servlet之间交换信息</strong>。常用的方法有getAttribute(String attName)、setAttribute(String attName , String attValue)和getInitParameter(String paramName)等。</li>
<li>config：javax.servlet.ServletConfig的实例，该实例代表该JSP的配置信息。常用的方法有getInitParameter(String paramName)和getInitParameternames()等方法。事实上，JSP页面通常无须配置，也就不存在配置信息。因此，该对象更多地在Servlet中有效。</li>
<li>exception：java.lang.Throwable的实例，该实例代表其他页面中的异常和错误。<strong>只有当页面是错误处理页面，即编译指令page的isErrorPage属性为true时，该对象才可以使用</strong>。常用的方法有getMessage()和printStackTrace()等。</li>
<li>out：javax.servlet.jsp.JspWriter的实例，该实例代表JSP页面的输出流，用于输出内容，形成HTML页面。</li>
<li>page：代表该页面本身，通常没有太大用处。也就是Servlet中的this，其类型就是生成的Servlet类，能用page的地方就可用this。</li>
<li>pageContext：javax.servlet.jsp.PageContext的实例，该对象代表该JSP页面上下文，使用该对象可以访问页面中的共享数据。常用的方法有getServletContext()和getServletConfig()等。</li>
<li>request：javax.servlet.http.HttpServletRequest的实例，该对象封装了一次请求，客户端的请求参数都被封装在该对象里。这是一个常用的对象，获取客户端请求参数必须使用该对象。常用的方法有getParameter(String paramName)、getParameterValues(String paramName)、setAttribute(String atttName,Object attrValue)、getAttribute(String attrName)和setCharacterEncoding(String env)等。</li>
<li>response：javax.servlet.http.HttpServletResponse的实例，代表服务器对客户端的响应。通常很少使用该对象直接响应，而是使用out对象，除非需要生成非字符响应。而response对象常用于重定向，常用的方法有getOutputStream()、sendRedirect(java.lang.String location)等。</li>
<li>session：javax.servlet.http.HttpSession的实例，该对象代表一次会话。当客户端浏览器与站点建立连接时，会话开始；当客户端关闭浏览器时，会话结束。常用的方法有：getAttribute(String attrName)、setAttribute(String attrName, Object attrValue)等。</li>
</ul>
<p>request、response是<code>_jspService()</code>方法的形参，其它都是其局部变量。</p>
<p><strong>由于jsp内置对象都是在<code>_jspService()</code>方法中完成初始化的，因此只能在jsp脚本、jsp输出表达式中使用这些内置变量。千万不要在jsp声明中使用它们</strong>。</p>
<h3 id="application">application</h3><p>对于每次客户端请求而言，<strong>Web服务器大致需要完成如下几个步骤</strong>：</p>
<ol>
<li>启动单独的线程。</li>
<li>使用I/O流读取用户的请求数据。</li>
<li>从请求数据中解析参数。</li>
<li>处理用户请求。</li>
<li>生成响应数据。</li>
<li>使用IO流向客户端发送请求数据。</li>
</ol>
<p>在上面6个步骤中，第1、2和6步是通用的，可以由Web服务器来完成，但第3、4和5步则存在差异：因为不同请求里包含的请求参数不同，处理用户请求的方式也不同，所生成的响应自然也不同。Web服务器会调用Servlet的<code>_jspService()</code>方法来完成第3、4和5步，<strong>当我们编写JSP页面时，页面里的静态内容、JSP脚本都会转换成<code>_jspService()</code>方法的执行代码，这些执行代码负责完成解析参数、处理请求、生成响应等业务功能，而Web服务器则负责完成多线程、网络通信等底层功能</strong>。</p>
<p>为了解决JSP、Servlet之间如何交换数据的问题，几乎所有Web服务器（包括Java、ASP、PHP、Ruby等）都会提供4个类似Map的结构，分别是application、session、request、page，并允许JSP、Servlet将数据放入这4个类似Map的结构中，并允许从这4个Map结构中取出数据。这4个Map结构的区别是范围不同。</p>
<ul>
<li>application：对于整个Web应用有效，一旦JSP、Servlet将数据放入application中，该数据将可以被该应用下其他所有的JSP、Servlet访问。</li>
<li>session：仅对一次会话有效，一旦JSP、Servlet将数据放入session中，该数据将可以被本次会话的其他所有的JSP、Servlet访问。</li>
<li>request：仅对本次请求有效，一旦JSP、Servlet将数据放入request中，该数据将可以被该次请求的其他JSP、Servlet访问。</li>
<li>page：仅对当前页面有效，一旦JSP、Servlet将数据放入page中，该数据只可以被当前页面的JSP脚本、声明部分访问。</li>
</ul>
<p>application对象通常有如下两个作用：</p>
<ul>
<li>在整个Web应用的多个JSP、Servlet之间共享数据。</li>
<li>访问Web应用的配置参数。</li>
</ul>
<ol>
<li><p>让多个jsp、servlet共享数据</p>
<p> application通过setAttribute(String attrName,Object value)方法将一个值设置成application的attrName属性，该属性的值对整个Web应用有效，因此该Web应用的每个JSP页面或Servlet都可以访问该属性，访问属性的方法为getAttribute(String attrName)。<br> <strong>由于在Servlet中并没有application内置对象，所以可以通过<code>ServletContext sc = getServletConfig().getServletContext()</code>显式获取了该Web应用的ServletContext实例</strong>，每个Web应用只有一个ServletContext实例，在JSP页面中可通过application内置对象访问该实例，而Servlet中则必须通过代码获取。<br> 编译Servlet时可能由于没有添加环境出现异常，如果安装了Java EE 6 SDK，只需将Java EE 6 SDK路径的javaee.jar文件添加到CLASSPATH环境变量中；如果没有安装Java EE SDK，可以将Tomcat 7的lib路径下的jsp-api.jar、servlet-api.jar两个文件添加到CLASSPATH环境变量中。<br> <strong>虽然使用application（即ServletContext实例）可以方便多个JSP、Servlet共享数据，但不要仅为了JSP、Servlet共享数据就将数据放入application中！由于application代表整个Web应用，所以通常只应该把Web应用的状态数据放入application里</strong>。</p>
</li>
<li><p>获得Web应用配置参数</p>
<p> 一些配置信息可以放在web.xml文件中，使用context-param元素配置，每个<context-param…>元素配置一个参数，该元素下有如下两个子元素。</context-param…></p>
<ul>
<li>param-name：配置Web参数名。</li>
<li>param-value：配置Web参数值。<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 配置第一个参数：user --&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="title">context-param</span>&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">param-name</span>&gt;</span>user<span class="tag">&lt;/<span class="title">param-name</span>&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">param-value</span>&gt;</span>root<span class="tag">&lt;/<span class="title">param-value</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">context-param</span>&gt;</span> </span><br><span class="line"><span class="comment">&lt;!-- 配置第二个参数：pass --&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="title">context-param</span>&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">param-name</span>&gt;</span>pass<span class="tag">&lt;/<span class="title">param-name</span>&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">param-value</span>&gt;</span>32147<span class="tag">&lt;/<span class="title">param-value</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">context-param</span>&gt;</span></span><br></pre></td></tr></table></figure>
之后可以通过application的 getInitParameter(String paramName)方法获取配置参数。<figure class="highlight mel"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;%</span><br><span class="line">String user = application.getInitParameter(<span class="string">"user"</span>);</span><br><span class="line">String <span class="keyword">pwd</span> = application.getInitParameter(<span class="string">"pass"</span>);</span><br><span class="line">out.println(user + <span class="string">" "</span> + <span class="keyword">pwd</span>);</span><br><span class="line"><span class="variable">%&gt;</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ol>
<h3 id="config">config</h3><p>config对象代表当前JSP配置信息，但JSP页面通常无须配置，因此也就不存在配置信息。该对象在JSP页面中比较少用，但在Servlet中则用处相对较大，因为Servlet需要在web.xml文件中进行配置，可以指定配置参数。</p>
<p>在jsp输出config的getServletName()方法的返回值为jsp，所有的JSP页面都有相同的名字：jsp</p>
<p>config对象是ServletConfig的实例，该接口用于获取配置参数的方法是getInitParameter(String paramName)</p>
<p>配置JSP也是在web.xml文件中进行的，JSP被当成Servlet配置，为Servlet配置参数使用init-param元素，该元素可以接受param-name和param-value两个子元素，分别指定参数名和参数值。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">servlet</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 指定Servlet名字 --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">servlet-name</span>&gt;</span>config<span class="tag">&lt;/<span class="title">servlet-name</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 指定将哪个JSP页面配置成Servlet --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">jsp-file</span>&gt;</span>/configTest2.jsp<span class="tag">&lt;/<span class="title">jsp-file</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 配置名为name的参数，值为yeeku --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">init-param</span>&gt;</span> </span><br><span class="line">        <span class="tag">&lt;<span class="title">param-name</span>&gt;</span>name<span class="tag">&lt;/<span class="title">param-name</span>&gt;</span> </span><br><span class="line">        <span class="tag">&lt;<span class="title">param-value</span>&gt;</span>yeeku<span class="tag">&lt;/<span class="title">param-value</span>&gt;</span> </span><br><span class="line">    <span class="tag">&lt;/<span class="title">init-param</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 配置名为age的参数，值为30 --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">init-param</span>&gt;</span> </span><br><span class="line">        <span class="tag">&lt;<span class="title">param-name</span>&gt;</span>age<span class="tag">&lt;/<span class="title">param-name</span>&gt;</span> </span><br><span class="line">        <span class="tag">&lt;<span class="title">param-value</span>&gt;</span>30<span class="tag">&lt;/<span class="title">param-value</span>&gt;</span> </span><br><span class="line">    <span class="tag">&lt;/<span class="title">init-param</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">servlet</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="title">servlet-mapping</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 指定将config Servlet配置到/config路径 --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">servlet-name</span>&gt;</span>config<span class="tag">&lt;/<span class="title">servlet-name</span>&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">url-pattern</span>&gt;</span>/config<span class="tag">&lt;/<span class="title">url-pattern</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">servlet-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>上面的配置文件片段为该Servlet（其实是JSP）配置了2个参数：name和age。上面的配置片段把configTest2.jsp页面配置成名为config的Servlet，并将该Servlet映射到/config处，这就允许我们通过/config来访问该页面。</p>
<p>通过config可以访问到web.xml文件中的配置参数。实际上，我们也可以直接访问configTest2.jsp页面。</p>
<p>如果希望JSP页面可以获取web.xml配置文件中的配置信息，则必须通过为该JSP配置的路径来访问该页面，因为只有这样访问JSP页面才会让配置参数起作用。</p>
<h3 id="exception">exception</h3><p>exception对象是Throwable的实例，代表JSP脚本中产生的错误和异常，是JSP页面异常机制的一部分。</p>
<p>exception对象仅在异常处理页面中才有效，即isErrorPage为true时。</p>
<p>编译为servlet后，这些脚本已经处于<code>_jspService()</code>方法的try块中。一旦try块捕捉到JSP脚本的异常，并且<code>_jspx_page_context</code>不为null，就会由该对象来处理该异常，如上面粗体字代码所示。<code>_jspx_page_context</code>对异常的处理也非常简单：如果该页面的page指令指定了errorPage属性，则将请求forward到errorPage属性指定的页面，否则使用系统页面来输出异常信息。只有jsp脚本、输出表达式才会对应于<code>_jspService()</code>方法里的代码，所以这两部分的代码无须处理checked异常。但是jsp的异常处理机制对jsp声明不起作用。</p>
<h3 id="out">out</h3><p>out对象代表一个页面输出流，通常用于在页面上输出变量值及常量。一般在使用输出表达式的地方，都可以使用out对象来达到同样效果。</p>
<h3 id="pageContext">pageContext</h3><p>这个对象代表页面上下文，该对象主要用于访问JSP之间的共享数据。使用pageContext可以访问page、request、session、application范围的变量。</p>
<p>pageContext是PageContext类的实例，它提供了如下两个方法来访问page、request、session、application范围的变量。</p>
<ul>
<li>getAttribute(String name)：取得page范围内的name属性。</li>
<li><p>getAttribute(String name,int scope)：取得指定范围内的name属性，其中scope可以是如下4个值。</p>
<ul>
<li>PageContext.PAGE_SCOPE：对应于page范围。</li>
<li>PageContext.REQUEST_SCOPE：对应于request范围。</li>
<li>PageContext.SESSION_SCOPE：对应于session范围。</li>
<li>PageContext.APPLICATION_SCOPE：对应于application范围。</li>
</ul>
</li>
</ul>
<p>与getAttribute()方法相对应，PageContext也提供了2个对应的setAttribute()方法，用于将指定变量放入page、request、session、application范围内。</p>
<p>pageContext还可用于获取其他内置对象，pageContext对象包含如下方法。</p>
<ul>
<li>ServletRequest getRequest()：获取request对象。</li>
<li>ServletResponse getResponse()：获取response对象。</li>
<li>ServletConfig getServletConfig()：获取config对象。</li>
<li>ServletContext getServletContext()：获取application对象。</li>
<li>HttpSession getSession()：获取session对象。</li>
</ul>
<p>因此一旦在JSP、Servlet编程中获取了pageContext对象，就可以通过它提供的上面方法来获取其他内置对象。</p>
<h3 id="request">request</h3><p>request对象是获取请求参数的重要途径。除此之外，request可代表本次请求范围，所以还可用于操作request范围的属性。</p>
<ol>
<li><p>获取请求头/请求参数</p>
<p> request是HttpServletRequest接口的实例，它提供了如下几个方法来获取请求参数。</p>
<ul>
<li>String getParameter(String paramName)：获取paramName请求参数的值。</li>
<li>Map getParameterMap()：获取所有请求参数名和参数值所组成的Map对象。</li>
<li>Enumeration getParameterNames()：获取所有请求参数名所组成的Enumeration对象。</li>
<li><p>String[] getParameterValues(String name)：paramName请求参数的值，当该请求参数有多个值时，该方法将返回多个值所组成的数组。</p>
<p>HttpServletRequest提供了如下方法来访问请求头。</p>
</li>
<li><p>String getHeader(String name)：根据指定请求头的值。</p>
</li>
<li>java.util.Enumeration<string> getHeaderNames()：获取所有请求头的名称。</string></li>
<li>java.util.Enumeration<string> getHeaders(String name)：获取指定请求头的多个值。</string></li>
<li><p>int getIntHeader(String name)：获取指定请求头的值，并将该值转为整数值。</p>
<p>对于开发人员来说，请求头和请求参数都是由用户发送到服务器的数据，区别在于请求头通常由浏览器自动添加，因此一次请求总是包含若干请求头；而请求参数则通常需要开发人员控制添加，让客户端发送请求参数通常分两种情况。</p>
<p><strong>GET方式的请求：直接在浏览器地址栏输入访问地址所发送的请求或提交表单发送请求时，该表单对应的form元素没有设置method属性，或设置method属性为get，这几种请求都是GET方式的请求。GET方式的请求会将请求参数的名和值转换成字符串，并附加在原URL之后，因此可以在地址栏中看到请求参数名和值。且GET请求传送的数据量较小，一般不能大于2KB</strong>。</p>
<p><strong>POST方式的请求：这种方式通常使用提交表单（由form HTML元素表示）的方式来发送，且需要设置form元素的method属性为post。POST方式传送的数据量较大，通常认为POST请求参数的大小不受限制，但往往取决于服务器的限制，POST请求传输的数据量总比GET传输的数据量大。而且POST方式发送的请求参数以及对应的值放在HTML HEADER中传输，用户不能在地址栏里看到请求参数值，安全性相对较高</strong>。</p>
<p>对比上面两种请求方式，由此可见我们通常应该采用POST方式发送请求。</p>
<p>并不是每个表单域都会生成请求参数的，而是有name属性的表单域才生成请求参数。关于表单域和请求参数的关系遵循如下4点：</p>
</li>
<li><p>每个有name属性的表单域对应一个请求参数。</p>
</li>
<li>如果有多个表单域有相同的name属性，则多个表单域只生成一个请求参数，只是该参数有多个值。</li>
<li>表单域的name属性指定请求参数名，value指定请求参数值。</li>
<li><p>如果某个表单域设置了disabled=”disabled”属性，则该表单域不再生成请求参数。</p>
<p>如果发送请求的表单页采用gb2312字符集，该表单页发送的请求也将采用gb2312字符集，所以本页面需要先执行如下方法。 <code>setCharacterEncoding(&quot;gb2312&quot;)</code>：设置request编码所用的字符集。<br>使用GET方法，如果请求参数值里包含非西欧字符，那么是不是应该先调用setCharacterEncoding()来设置request编码的字符集呢？读者可以试一下。答案是不行，如果GET方式的请求值里包含了非西欧字符，则获取这些参数比较复杂。为了获取GET请求里的中文参数值，必须借助于java.net.URLDecoder类。</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;<span class="built_in">%</span></span><br><span class="line"><span class="comment">//获取请求里包含的查询字符串  </span></span><br><span class="line">String rawQueryStr = request.getQueryString<span class="params">()</span>;  </span><br><span class="line">out.println<span class="params">(<span class="string">"原始查询字符串为："</span> + rawQueryStr + <span class="string">"&lt;hr/&gt;"</span>)</span>;  </span><br><span class="line"><span class="comment">//使用URLDecoder解码字符串  </span></span><br><span class="line">String queryStr = java.net.URLDecoder.decode<span class="params">(rawQueryStr , <span class="string">"gbk"</span>)</span>; </span><br><span class="line">out.println<span class="params">(<span class="string">"解码后的查询字符串为："</span> + queryStr + <span class="string">"&lt;hr/&gt;"</span>)</span>;</span><br><span class="line"><span class="built_in">%</span>&gt;</span><br></pre></td></tr></table></figure>
<p>可通过如下代码来取得name请求参数的参数值。</p>
<figure class="highlight processing"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;%</span><br><span class="line"><span class="comment">//获取原始的请求参数值  </span></span><br><span class="line"><span class="keyword">String</span> rawName = request.getParameter(<span class="string">"name"</span>);  </span><br><span class="line"><span class="comment">//将请求参数值使用ISO-8859-1字符串分解成字节数组  </span></span><br><span class="line"><span class="built_in">byte</span>[] rawBytes = rawName.getBytes(<span class="string">"ISO-8859-1"</span>);  </span><br><span class="line"><span class="comment">//将字节数组重新解码成字符串  </span></span><br><span class="line"><span class="keyword">String</span> name = <span class="keyword">new</span> <span class="keyword">String</span>(rawBytes , <span class="string">"gb2312"</span>); </span><br><span class="line">%&gt;</span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
<li><p>操作request范围的属性</p>
<p> HttpServletRequest还包含如下两个方法，用于设置和获取request范围的属性。</p>
<ul>
<li>setAttribute(String attName , Object attValue)：将attValue设置成request范围的属性。</li>
<li>Object getAttribute(String attName)：获取request范围的属性。<br>当forward用户请求时，请求的参数和请求属性都不会丢失。通过<code>setAttribute</code>方法设置的属性也不会丢失。</li>
</ul>
</li>
<li><p>执行forward或include</p>
<p> request还有一个功能就是执行forward和include，也就是代替JSP所提供的forward和include动作指令。<br> HttpServletRequest类提供了一个getRequestDispatcher (String path)方法，其中path就是希望forward或者include的目标路径，该方法返回RequestDispatcher，该对象提供了如下两个方法。</p>
<ul>
<li>forward(ServletRequest request, ServletResponse response)：执行forward。</li>
<li><p>include(ServletRequest request, ServletResponse response)：执行include。</p>
<p>使用request的getRequestDispatcher(String path)方法时，该path字符串必须以斜线开头。</p>
</li>
</ul>
</li>
</ol>
<h3 id="response">response</h3><p>response代表服务器对客户端的响应。大部分时候，程序无须使用response来响应客户端请求，因为有个更简单的响应对象—out，它代表页面输出流，直接使用out生成响应更简单。</p>
<p>但out是JspWriter的实例，JspWriter是Writer的子类，Writer是字符流，无法输出非字符内容。假如需要在JSP页面中动态生成一幅位图、或者输出一个PDF文档，使用out作为响应对象将无法完成，此时必须使用response作为响应输出。</p>
<p>除此之外，还可以使用response来重定向请求，以及用于向客户端增加Cookie。</p>
<ol>
<li><p>response响应生成非字符响应</p>
<p> response是HttpServletResponse接口的实例，该接口提供了一个getOutputStream()方法，该方法返回响应输出字节流。下面的方法可以输出图像。</p>
 <figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">&lt;<span class="built_in">%</span>-- 通过contentType属性指定响应数据是图片 --<span class="built_in">%</span>&gt; </span><br><span class="line">&lt;<span class="built_in">%</span>@ page contentType=<span class="string">"image/jpeg"</span> language=<span class="string">"java"</span><span class="built_in">%</span>&gt; </span><br><span class="line">&lt;<span class="built_in">%</span>@ page <span class="built_in">import</span>=<span class="string">"java.awt.image.*,javax.imageio.*,java.io.*,java.awt.*"</span><span class="built_in">%</span>&gt; </span><br><span class="line">&lt;<span class="built_in">%</span>  </span><br><span class="line"><span class="comment">//创建BufferedImage对象  </span></span><br><span class="line">BufferedImage image = new BufferedImage<span class="params">(<span class="number">340</span> , <span class="number">160</span>, BufferedImage.TYPE_INT_RGB)</span>;  </span><br><span class="line"><span class="comment">//以Image对象获取Graphics对象  </span></span><br><span class="line">Graphics g = image.getGraphics<span class="params">()</span>;  </span><br><span class="line"><span class="comment">//使用Graphics画图，所画的图像将会出现在image对象中  </span></span><br><span class="line">g.fillRect<span class="params">(<span class="number">0</span>,<span class="number">0</span>,<span class="number">400</span>,<span class="number">400</span>)</span>;  </span><br><span class="line"><span class="comment">//设置颜色：红  </span></span><br><span class="line">g.setColor<span class="params">(new Color<span class="params">(<span class="number">255</span>,<span class="number">0</span>,<span class="number">0</span>)</span>)</span>;  </span><br><span class="line"><span class="comment">//画出一段弧  </span></span><br><span class="line">g.fillArc<span class="params">(<span class="number">20</span>, <span class="number">20</span>, <span class="number">100</span>,<span class="number">100</span>, <span class="number">30</span>, <span class="number">120</span>)</span>;  </span><br><span class="line"><span class="comment">//设置颜色：绿  </span></span><br><span class="line">g.setColor<span class="params">(new Color<span class="params">(<span class="number">0</span> , <span class="number">255</span>, <span class="number">0</span>)</span>)</span>;  </span><br><span class="line"><span class="comment">//画出一段弧  </span></span><br><span class="line">g.fillArc<span class="params">(<span class="number">20</span>, <span class="number">20</span>, <span class="number">100</span>,<span class="number">100</span>, <span class="number">150</span>, <span class="number">120</span>)</span>;  </span><br><span class="line"><span class="comment">//设置颜色：蓝  </span></span><br><span class="line">g.setColor<span class="params">(new Color<span class="params">(<span class="number">0</span> , <span class="number">0</span>, <span class="number">255</span>)</span>)</span>;  </span><br><span class="line"><span class="comment">//画出一段弧  </span></span><br><span class="line">g.fillArc<span class="params">(<span class="number">20</span>, <span class="number">20</span>, <span class="number">100</span>,<span class="number">100</span>, <span class="number">270</span>, <span class="number">120</span>)</span>;  </span><br><span class="line"><span class="comment">//设置颜色：黑  </span></span><br><span class="line">g.setColor<span class="params">(new Color<span class="params">(<span class="number">0</span>,<span class="number">0</span>,<span class="number">0</span>)</span>)</span>;  </span><br><span class="line">g.setFont<span class="params">(new Font<span class="params">(<span class="string">"Arial Black"</span>, Font.PLAIN, <span class="number">16</span>)</span>)</span>;  </span><br><span class="line"><span class="comment">//画出三个字符串  </span></span><br><span class="line">g.drawString<span class="params">(<span class="string">"red:climb"</span> , <span class="number">200</span> , <span class="number">60</span>)</span>;  </span><br><span class="line">g.drawString<span class="params">(<span class="string">"green:swim"</span> , <span class="number">200</span> , <span class="number">100</span>)</span>;  </span><br><span class="line">g.drawString<span class="params">(<span class="string">"blue:jump"</span> , <span class="number">200</span> , <span class="number">140</span>)</span>;  </span><br><span class="line">g.dispose<span class="params">()</span>;  </span><br><span class="line"><span class="comment">//将图像输出到页面的响应  </span></span><br><span class="line">ImageIO.write<span class="params">(image , <span class="string">"jpg"</span> , response.getOutputStream<span class="params">()</span>)</span>;  </span><br><span class="line"><span class="built_in">%</span>&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p>重定向</p>
<p> 重定向是response的另外一个用处，与forward不同的是，重定向会丢失所有的请求参数和request范围的属性，因为重定向将生成第二次请求，与前一次请求不在同一个request范围内，所以发送一次请求的请求参数和request范围的属性全部丢失。</p>
<p> HttpServletResponse提供了一个sendRedirect(String path)方法，该方法用于重定向到path资源，即重新向path资源发送请求。</p>
<p> forward和redirect对比</p>
<p> <strong>执行redirect后生成第二次请求，而forward依然是上一次请求。<br> redirect的目标页面不能访问原请求的请求参数，因为是第二次请求了，所有原请求的请求参数、request范围的属性全部丢失。forward的目标页面可以访问原请求的请求参数，因为依然是同一次请求，所有原请求的请求参数、request范围的属性全部存在。<br> 地址栏改为重定向的目标URL。相当于在浏览器地址栏里输入新的URL后按回车键。而forward地址栏里请求的URL不会改变</strong></p>
</li>
<li><p>增加Cookie</p>
<p> <strong>Cookie与session的不同之处在于：session会随浏览器的关闭而失效，但Cookie会一直存放在客户端机器上，除非超出Cookie的生命期限</strong>。</p>
<p> 增加Cookie也是使用response内置对象完成的，response对象提供了如下方法。<br> void addCookie(Cookie cookie)：增加Cookie。<br> 增加Cookie请按如下步骤进行。</p>
<ul>
<li>创建Cookie实例，Cookie的构造器为Cookie(String name, String value)。</li>
<li>设置Cookie的生命期限，即该Cookie在多长时间内有效。</li>
<li>向客户端写Cookie。<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&lt;<span class="built_in">%</span></span><br><span class="line"><span class="comment">//增加cookie</span></span><br><span class="line">String name = request.getParameter<span class="params">(<span class="string">"name"</span>)</span>;  </span><br><span class="line"><span class="comment">//以获取到的请求参数为值，创建一个Cookie对象  </span></span><br><span class="line">Cookie c = new Cookie<span class="params">(<span class="string">"username"</span> , name)</span>;  </span><br><span class="line"><span class="comment">//设置Cookie对象的生存期限  </span></span><br><span class="line">c.setMaxAge<span class="params">(<span class="number">24</span> * <span class="number">3600</span>)</span>;  </span><br><span class="line"><span class="comment">//向客户端增加Cookie对象  </span></span><br><span class="line">response.addCookie<span class="params">(c)</span>;  </span><br><span class="line"><span class="built_in">%</span>&gt;</span><br></pre></td></tr></table></figure>
访问客户端Cookie使用request对象，request对象提供了getCookies()方法，该方法将返回客户端机器上所有Cookie组成的数组，遍历该数组的每个元素，找到希望访问的Cookie即可。<br>使用Cookie对象必须设置其生存期限，否则Cookie将会随浏览器的关闭而自动消失。<br>默认情况下，Cookie值不允许出现中文字符，如果我们需要值为中文内容的Cookie怎么办呢？同样可以借助于java.net.URLEncoder先对中文字符串进行编码，将编码后的结果设为Cookie值。当程序要读取Cookie时，则应该先读取，然后使用java.net.URLDecoder对其进行解码。</li>
</ul>
</li>
</ol>
<h3 id="session">session</h3><p><strong>session对象也是一个非常常用的对象，这个对象代表一次用户会话。一次用户会话的含义是：从客户端浏览器连接服务器开始，到客户端浏览器与服务器断开为止，这个过程就是一次会话</strong>。</p>
<p>session通常用于跟踪用户的会话信息，如判断用户是否登录系统，或者在购物车应用中，用于跟踪用户购买的商品等。</p>
<p>session对象是HttpSession的实例，HttpSession有如下两个常用的方法。</p>
<p>setAttribute(String attName，Object attValue)：设置session范围内attName属性的值为attValue。<br>getAttribute(String attName)：返回session范围内attName属性的值。</p>
<p>关于session还有一点需要指出，<strong>session机制通常用于保存客户端的状态信息，这些状态信息需要保存到Web服务器的硬盘上，所以要求session里的属性值必须是可序列化的，否则将会引发不可序列化的异常</strong>。</p>
<p>session的属性值可以是任何可序列化的Java对象。</p>
<h2 id="servlet介绍">servlet介绍</h2><h3 id="Servlet的开发">Servlet的开发</h3><p>前面介绍的JSP的本质就是Servlet，Servlet通常被称为服务器端小程序，是运行在服务器端的程序，用于处理及响应客户端的请求。</p>
<p>Servlet是个特殊的Java类，这个Java类必须继承HttpServlet。每个Servlet可以响应客户端的请求。Servlet提供不同的方法用于响应客户端请求。</p>
<ul>
<li>doGet：用于响应客户端的GET请求。</li>
<li>doPost：用于响应客户端的POST请求。</li>
<li>doPut：用于响应客户端的PUT请求。</li>
<li>doDelete：用于响应客户端的DELETE请求。</li>
</ul>
<p>事实上，客户端的请求通常只有GET和POST两种，Servlet为了响应这两种请求，必须重写doGet()和doPost()两个方法。如果Servlet为了响应4个方式的请求，则需要同时重写上面的4个方法。</p>
<p>大部分时候，Servlet对于所有请求的响应都是完全一样的。此时，可以采用重写一个方法来代替上面的几个方法：只需重写service()方法即可响应客户端的所有请求。</p>
<p>另外，HttpServlet还包含两个方法。</p>
<ul>
<li>init(ServletConfig config)：创建Servlet实例时，调用该方法的初始化Servlet资源。</li>
<li>destroy()：销毁Servlet实例时，自动调用该方法的回收资源。</li>
</ul>
<p>通常无须重写init()和destroy()两个方法，除非需要在初始化Servlet时，完成某些资源初始化的方法，才考虑重写init方法。如果需要在销毁Servlet之前，先完成某些资源的回收，比如关闭数据库连接等，才需要重写destroy方法。</p>
<p>不用为Servlet类编写构造器，如果需要对Servlet执行初始化操作，应将初始化操作放在Servlet的init()方法中定义。如果重写了init(ServletConfig config)方法，则应在重写该方法的第一行调用super.init(config)。该方法将调用HttpServlet的init方法。</p>
<p>Servlet和JSP的区别在于：</p>
<ul>
<li>Servlet中没有内置对象，原来JSP中的内置对象都必须由程序显式创建。</li>
<li>对于静态的HTML标签，Servlet都必须使用页面输出流逐行输出。</li>
</ul>
<p><strong>普通Servlet类里的service()方法的作用，完全等同于JSP生成Servlet类的<code>_jspService()</code>方法。因此原JSP页面的JSP脚本、静态HTML内容，在普通Servlet里都应该转换成service()方法的代码或输出语句；原JSP声明中的内容，对应为在Servlet中定义的成员变量或成员方法</strong>。</p>
<h3 id="servlet的配置">servlet的配置</h3><p>编辑好的Servlet源文件需编译成class文件才能响应用户请求。将编译后的.class文件放在WEB-INF/classes路径下，如果Servlet有包，则还应该将class文件放在对应的包路径下。</p>
<p>如果需要直接采用javac命令来编译Servlet类，则必须将Servlet API接口和类添加到系统的CLASSPATH环境变量里。也就是将Tomcat 7安装目录下lib目录中servlet-api. jar和jsp-api.jar添加到CLASSPATH环境变量中。</p>
<p>为了让Servlet能响应用户请求，还必须将Servlet配置在Web应用中。配置Servlet时，需要修改web.xml文件。</p>
<p>从Servlet 3.0开始，配置Servlet有两种方式：</p>
<ul>
<li>在Servlet类中使用@WebServlet Annotation进行配置。</li>
<li>通过在web.xml文件中进行配置。</li>
</ul>
<p>上面开发Servlet类时使用了@WebServlet Annotation修饰该Servlet类，使用@WebServlet时可指定如表所示的常用属性。</p>
<p>属    性          | 是否必需 | 说    明<br>asyncSupported    | 否       | 指定该Servlet是否支持异步操作模式。关于Servlet的异步调用请参考2.15节<br>displayName       | 否       | 指定该Servlet的显示名<br>initParams        | 否       | 用于为该Servlet配置参数<br>loadOnStartup     | 否       | 用于将该Servlet配置成 load-on-startup的Servlet<br>name              | 否       | 指定该Servlet的名称<br>urlPatterns/value | 否       | 这两个属性的作用完全相同。都指定该Servlet处理的URL</p>
<p>如果打算使用Annotation来配置Servlet，有两点需要指出：</p>
<ul>
<li>不要在web.xml文件的根元素（<code>&lt;web-app.../&gt;</code>）中指定metadata-complete=”true”。</li>
<li>不要在web.xml文件中配置该Servlet。</li>
</ul>
<p>如果打算使用web.xml文件来配置该Servlet，则需要配置如下两个部分。</p>
<ul>
<li>配置Servlet的名字：对应web.xml文件中的<code>&lt;servlet/&gt;</code>元素。</li>
<li>配置Servlet的URL：对应web.xml文件中的<code>&lt;servlet-mapping/&gt;</code>元素。这一步是可选的。但如果没有为Servlet配置URL，则该Servlet不能响应用户请求。</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 配置Servlet的名字 --&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="title">servlet</span>&gt;</span>     </span><br><span class="line"><span class="comment">&lt;!-- 指定Servlet的名字，相当于指定@WebServlet的name属性 --&gt;</span>     </span><br><span class="line"><span class="tag">&lt;<span class="title">servlet-name</span>&gt;</span>firstServlet<span class="tag">&lt;/<span class="title">servlet-name</span>&gt;</span>     </span><br><span class="line"><span class="comment">&lt;!-- 指定Servlet的实现类 --&gt;</span>     </span><br><span class="line"><span class="tag">&lt;<span class="title">servlet-class</span>&gt;</span>lee.FirstServlet<span class="tag">&lt;/<span class="title">servlet-class</span>&gt;</span> <span class="tag">&lt;/<span class="title">servlet</span>&gt;</span> </span><br><span class="line"><span class="comment">&lt;!-- 配置Servlet的URL --&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="title">servlet-mapping</span>&gt;</span>     </span><br><span class="line"><span class="comment">&lt;!-- 指定Servlet的名字 --&gt;</span>     </span><br><span class="line"><span class="tag">&lt;<span class="title">servlet-name</span>&gt;</span>firstServlet<span class="tag">&lt;/<span class="title">servlet-name</span>&gt;</span>     </span><br><span class="line"><span class="comment">&lt;!-- 指定Servlet映射的URL地址，相当于指定@WebServlet的urlPatterns属性--&gt;</span>    <span class="tag">&lt;<span class="title">url-pattern</span>&gt;</span>/aa<span class="tag">&lt;/<span class="title">url-pattern</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">servlet-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>通过注解<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">@<span class="function"><span class="title">WebServlet</span><span class="params">(name=<span class="string">"firstServlet"</span>, urlPatterns=&#123;<span class="string">"/firstServlet"</span>&#125;)</span></span></span><br></pre></td></tr></table></figure></p>
<h3 id="JSP/Servlet的生命周期">JSP/Servlet的生命周期</h3><p>创建Servlet实例有两个时机。</p>
<ul>
<li>客户端第一次请求某个Servlet时，系统创建该Servlet的实例：大部分的Servlet都是这种Servlet。</li>
<li>Web应用启动时立即创建Servlet实例，即load-on-startup Servlet。</li>
</ul>
<p><strong>每个Servlet的运行都遵循如下生命周期</strong>。</p>
<ol>
<li>创建Servlet实例。</li>
<li>Web容器调用Servlet的init方法，对Servlet进行初始化。</li>
<li>Servlet初始化后，将一直存在于容器中，用于响应客户端请求。如果客户端发送GET请求，容器调用Servlet的doGet方法处理并响应请求；如果客户端发送POST请求，容器调用Servlet的doPost方法处理并响应请求。或者统一使用service()方法处理来响应用户请求。</li>
<li>Web容器决定销毁Servlet时，先调用Servlet的destroy方法，通常在关闭Web应用之时销毁Servlet。</li>
</ol>
<h3 id="load-on-startup_Servlet">load-on-startup Servlet</h3><p>配置load-on-startup的Servlet有两种方式：</p>
<ul>
<li>在web.xml文件中通过<code>&lt;servlet.../&gt;</code>元素的<code>&lt;load-on-startup.../&gt;</code>子元素进行配置。</li>
<li>通过@WebServlet Annotation的loadOnStartup属性指定。</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">servlet</span>&gt;</span>     </span><br><span class="line"><span class="comment">&lt;!-- Servlet名 --&gt;</span>     </span><br><span class="line"><span class="tag">&lt;<span class="title">servlet-name</span>&gt;</span>timerServlet<span class="tag">&lt;/<span class="title">servlet-name</span>&gt;</span>     </span><br><span class="line"><span class="comment">&lt;!-- Servlet的实现类 --&gt;</span>     </span><br><span class="line"><span class="tag">&lt;<span class="title">servlet-class</span>&gt;</span>lee.TimerServlet<span class="tag">&lt;/<span class="title">servlet-class</span>&gt;</span>     </span><br><span class="line"><span class="comment">&lt;!-- 配置应用启动时，创建Servlet实例，相当于指定@WebServlet的loadOnStartup属性--&gt;</span>     </span><br><span class="line"><span class="tag">&lt;<span class="title">load-on-startup</span>&gt;</span>1<span class="tag">&lt;/<span class="title">load-on-startup</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">servlet</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>通过注解<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">@<span class="function"><span class="title">WebServlet</span><span class="params">(loadOnStartup=<span class="number">1</span>)</span></span></span><br></pre></td></tr></table></figure></p>
<h3 id="访问Servlet的配置参数">访问Servlet的配置参数</h3><p>为Servlet配置参数有两种方式：</p>
<ul>
<li>通过@WebServlet的initParams属性来指定。</li>
<li>通过在web.xml文件的<code>&lt;servlet.../&gt;</code>元素中添加<code>&lt;init-param.../&gt;</code>子元素来指定。</li>
</ul>
<p>访问Servlet配置参数通过ServletConfig对象完成，ServletConfig提供如下方法。<br>java.lang.String getInitParameter(java.lang.String name)：用于获取初始化参数。<br>JSP的内置对象config就是此处的ServletConfig。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">servlet</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 配置Servlet名 --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">servlet-name</span>&gt;</span>testServlet<span class="tag">&lt;/<span class="title">servlet-name</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 指定Servlet的实现类 --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">servlet-class</span>&gt;</span>lee.TestServlet<span class="tag">&lt;/<span class="title">servlet-class</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 配置Servlet的初始化参数：user --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">init-param</span>&gt;</span> </span><br><span class="line">        <span class="tag">&lt;<span class="title">param-name</span>&gt;</span>user<span class="tag">&lt;/<span class="title">param-name</span>&gt;</span> </span><br><span class="line">        <span class="tag">&lt;<span class="title">param-value</span>&gt;</span>root<span class="tag">&lt;/<span class="title">param-value</span>&gt;</span> </span><br><span class="line">    <span class="tag">&lt;/<span class="title">init-param</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 配置Servlet的初始化参数：pass --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">init-param</span>&gt;</span> </span><br><span class="line">        <span class="tag">&lt;<span class="title">param-name</span>&gt;</span>pass<span class="tag">&lt;/<span class="title">param-name</span>&gt;</span> </span><br><span class="line">        <span class="tag">&lt;<span class="title">param-value</span>&gt;</span>32147<span class="tag">&lt;/<span class="title">param-value</span>&gt;</span> </span><br><span class="line">    <span class="tag">&lt;/<span class="title">init-param</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">servlet</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="title">servlet-mapping</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 确定Servlet名 --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">servlet-name</span>&gt;</span>testServlet<span class="tag">&lt;/<span class="title">servlet-name</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 配置Servlet映射的URL --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">url-pattern</span>&gt;</span>/testServlet<span class="tag">&lt;/<span class="title">url-pattern</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">servlet-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>通过注解<br><figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">@WebServlet</span>(name=<span class="string">"testServlet"</span> </span><br><span class="line">    , urlPatterns=&#123;<span class="string">"/testServlet"</span>&#125;  </span><br><span class="line">    , initParams=&#123;  </span><br><span class="line">        <span class="variable">@WebInitParam</span>(name=<span class="string">"user"</span>, value=<span class="string">"root"</span>),  </span><br><span class="line">        <span class="variable">@WebInitParam</span>(name=<span class="string">"pass"</span>, value=<span class="string">"32147"</span>)&#125;)</span><br></pre></td></tr></table></figure></p>
<h3 id="使用Servlet作为控制器">使用Servlet作为控制器</h3><p>在标准的MVC模式中，Servlet仅作为控制器使用。Java EE应用架构正是遵循MVC模式的，对于遵循MVC模式的Java EE应用而言，JSP仅作为表现层（View）技术，其作用有两点：</p>
<ul>
<li>负责收集用户请求参数。</li>
<li>将应用的处理结果、状态数据呈现给用户。</li>
</ul>
<p>Servlet则仅充当控制器（Controller）角色，它的作用类似于调度员：所有用户请求都发送给 Servlet，Servlet调用Model来处理用户请求，并调用JSP来呈现处理结果；或者Servlet直接调用JSP将应用的状态数据呈现给用户。</p>
<p>Model通常由JavaBean来充当，所有业务逻辑、数据访问逻辑都在Model中实现。实际上隐藏在Model下的可能还有很多丰富的组件，例如DAO组件、领域对象等。</p>
<p>下面是MVC中各个角色的对应组件。</p>
<p>M：Model，即模型，对应JavaBean。<br>V：View，即视图，对应JSP页面。<br>C：Controller，即控制器，对应Servlet。</p>
<h2 id="JSP_2的自定义标签">JSP 2的自定义标签</h2><p>在JSP 2中开发标签库只需如下几个步骤。</p>
<ul>
<li>开发自定义标签处理类；</li>
<li>建立一个<code>*.tld</code>文件，每个<code>*.tld</code>文件对应一个标签库，每个标签库可包含多个标签；</li>
<li>在JSP文件中使用自定义标签。</li>
</ul>
<h3 id="开发自定义标签类">开发自定义标签类</h3><p>自定义标签类应该继承一个父类：javax.servlet.jsp.tagext.SimpleTagSupport，除此之外，JSP自定义标签类还有如下要求：</p>
<ul>
<li>如果标签类包含属性，每个属性都有对应的getter和setter方法。</li>
<li>重写doTag()方法，这个方法负责生成页面内容。</li>
</ul>
<h3 id="建立TLD文件">建立TLD文件</h3><p>TLD是Tag Library Definition的缩写，即标签库定义，文件的后缀是tld，每个TLD文件对应一个标签库，一个标签库中可包含多个标签。TLD文件也称为标签库定义文件。</p>
<p>标签库定义文件的根元素是taglib，它可以包含多个tag子元素，每个tag子元素都定义一个标签。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="GBK"?&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="title">taglib</span> <span class="attribute">xmlns</span>=<span class="value">"http://java.sun.com/xml/ns/j2ee"</span> </span><br><span class="line"><span class="attribute">xmlns:xsi</span>=<span class="value">"http://www.w3.org/2001/XMLSchema-instance"</span>     </span><br><span class="line"><span class="attribute">xsi:schemaLocation</span>=<span class="value">"http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd"</span>     </span><br><span class="line"><span class="attribute">version</span>=<span class="value">"2.0"</span>&gt;</span>     </span><br><span class="line"><span class="tag">&lt;<span class="title">tlib-version</span>&gt;</span>1.0<span class="tag">&lt;/<span class="title">tlib-version</span>&gt;</span>     </span><br><span class="line"><span class="tag">&lt;<span class="title">short-name</span>&gt;</span>mytaglib<span class="tag">&lt;/<span class="title">short-name</span>&gt;</span>     </span><br><span class="line"><span class="comment">&lt;!-- 定义该标签库的URI --&gt;</span>     </span><br><span class="line"><span class="tag">&lt;<span class="title">uri</span>&gt;</span>http://www.crazyit.org/mytaglib<span class="tag">&lt;/<span class="title">uri</span>&gt;</span>     </span><br><span class="line"><span class="comment">&lt;!-- 定义第一个标签 --&gt;</span>     </span><br><span class="line"><span class="tag">&lt;<span class="title">tag</span>&gt;</span>         </span><br><span class="line"><span class="comment">&lt;!-- 定义标签名 --&gt;</span>         </span><br><span class="line"><span class="tag">&lt;<span class="title">name</span>&gt;</span>helloWorld<span class="tag">&lt;/<span class="title">name</span>&gt;</span>         </span><br><span class="line"><span class="comment">&lt;!-- 定义标签处理类 --&gt;</span>         </span><br><span class="line"><span class="tag">&lt;<span class="title">tag-class</span>&gt;</span>lee.HelloWorldTag<span class="tag">&lt;/<span class="title">tag-class</span>&gt;</span>         </span><br><span class="line"><span class="comment">&lt;!-- 定义标签体为空 --&gt;</span>         </span><br><span class="line"><span class="tag">&lt;<span class="title">body-content</span>&gt;</span>empty<span class="tag">&lt;/<span class="title">body-content</span>&gt;</span>     </span><br><span class="line"><span class="tag">&lt;/<span class="title">tag</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">taglib</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>taglib下有如下三个子元素。</p>
<ul>
<li>tlib-version：指定该标签库实现的版本，这是一个作为标识的内部版本号，对程序没有太大的作用。</li>
<li>short-name：该标签库的默认短名，该名称通常也没有太大的用处。</li>
<li>uri：这个属性非常重要，它指定该标签库的URI，相当于指定该标签库的唯一标识。如上面斜体字代码所示，JSP页面中使用标签库时就是根据该URI属性来定位标签库的。</li>
</ul>
<p>除此之外，taglib元素下可以包含多个tag元素，每个tag元素定义一个标签，tag元素下允许出现如下常用子元素。</p>
<ul>
<li>name：该标签库的名称，这个子元素很重要，JSP页面中就是根据该名称来使用此标签的。</li>
<li>tag-class：指定标签的处理类，毋庸置疑，这个子元素非常重要，它指定了标签由哪个标签处理类来处理。</li>
<li>body-content：这个子元素也很重要，它指定标签体内容。该子元素的值可以是如下几个。<ul>
<li>tagdependent：指定标签处理类自己负责处理标签体。</li>
<li>empty：指定该标签只能作为空标签使用。</li>
<li>scriptless：指定该标签的标签体可以是静态HTML元素、表达式语言，但不允许出现JSP脚本。</li>
<li>JSP：指定该标签的标签体可以使用JSP脚本。</li>
<li>dynamic-attributes：指定该标签是否支持动态属性。只有当定义动态属性标签时才需要该子元素。</li>
</ul>
</li>
</ul>
<p>因为JSP 2规范不再推荐使用JSP脚本，所以JSP 2自定义标签的标签体中不能包含JSP脚本。所以，实际上body-content元素的值不可以是JSP。</p>
<p>定义了上面的标签库定义文件后，将标签库文件放在Web应用的WEB-INF路径或任意子路径下，Java Web规范会自动加载该文件，则该文件定义的标签库也将生效。</p>
<h3 id="使用标签库">使用标签库</h3><p>在JSP页面中确定指定的标签需要两点。</p>
<ul>
<li>标签库URI：确定使用哪个标签库。</li>
<li>标签名：确定使用哪个标签。</li>
</ul>
<p>使用标签库分成以下两个步骤。</p>
<ul>
<li>导入标签库：使用taglib编译指令导入标签库，就是将标签库和指定前缀关联起来。</li>
<li>使用标签：在JSP页面中使用自定义标签。</li>
</ul>
<p>taglib的语法格式如下：<br><figure class="highlight gcode"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;<span class="preprocessor">%</span>@ taglib uri=<span class="string">"tagliburi"</span> prefix=<span class="string">"tagPrefix"</span> <span class="preprocessor">%</span>&gt;</span><br></pre></td></tr></table></figure></p>
<p>其中uri属性确定标签库的URI，这个URI可以确定一个标签库。而prefix属性指定标签库前缀，即所有使用该前缀的标签将由此标签库处理。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">%@</span> <span class="attribute">page</span> <span class="attribute">contentType</span>=<span class="value">"text/html; charset=GBK"</span> <span class="attribute">language</span>=<span class="value">"java"</span> <span class="attribute">errorPage</span>=<span class="value">""</span> %&gt;</span> </span><br><span class="line"><span class="comment">&lt;!-- 导入标签库，指定mytag前缀的标签，由http://www.crazyit.org/mytaglib的标签库处理 --&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="title">%@</span> <span class="attribute">taglib</span> <span class="attribute">uri</span>=<span class="value">"http://www.crazyit.org/mytaglib"</span> <span class="attribute">prefix</span>=<span class="value">"mytag"</span><span class="value">%</span>&gt;</span> </span><br><span class="line"><span class="doctype">&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="title">html</span> <span class="attribute">xmlns</span>=<span class="value">"http://www.w3.org/1999/xhtml"</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="title">head</span>&gt;</span><span class="tag">&lt;<span class="title">title</span>&gt;</span>自定义标签示范<span class="tag">&lt;/<span class="title">title</span>&gt;</span><span class="tag">&lt;/<span class="title">head</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="title">body</span> <span class="attribute">bgcolor</span>=<span class="value">"#ffffc0"</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="title">h2</span>&gt;</span>下面显示的是自定义标签中的内容<span class="tag">&lt;/<span class="title">h2</span>&gt;</span> </span><br><span class="line"><span class="comment">&lt;!-- 使用标签 ，其中mytag是标签前缀，根据taglib的编译指令，mytag前缀将由http://www.crazyit.org/mytaglib的标签库处理 --&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="title">mytag:helloWorld</span>/&gt;</span><span class="tag">&lt;<span class="title">br</span>/&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">body</span>&gt;</span> <span class="tag">&lt;/<span class="title">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="带属性的标签">带属性的标签</h3><p>带属性标签必须为每个属性提供对应的setter和getter方法。</p>
<p>对于有属性的标签，需要为<code>&lt;tag.../&gt;</code>元素增加<code>&lt;attribute.../&gt;</code>子元素，每个attribute子元素定义一个标签属性。<code>&lt;attribute.../&gt;</code>子元素通常还需要指定如下几个子元素。</p>
<ul>
<li>name：设置属性名，子元素的值是字符串内容。</li>
<li>required：设置该属性是否为必需属性，该子元素的值是true或false。</li>
<li>fragment：设置该属性是否支持JSP脚本、表达式等动态内容，子元素的值是true或false。</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">tag</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 定义标签名 --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">name</span>&gt;</span>tagname<span class="tag">&lt;/<span class="title">name</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 定义标签处理类 --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">tag-class</span>&gt;</span>lee.Tag<span class="tag">&lt;/<span class="title">tag-class</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 定义标签体为空 --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">body-content</span>&gt;</span>empty<span class="tag">&lt;/<span class="title">body-content</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 配置标签属性:user --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">attribute</span>&gt;</span> </span><br><span class="line">        <span class="tag">&lt;<span class="title">name</span>&gt;</span>user<span class="tag">&lt;/<span class="title">name</span>&gt;</span> </span><br><span class="line">        <span class="tag">&lt;<span class="title">required</span>&gt;</span>true<span class="tag">&lt;/<span class="title">required</span>&gt;</span> </span><br><span class="line">        <span class="tag">&lt;<span class="title">fragment</span>&gt;</span>true<span class="tag">&lt;/<span class="title">fragment</span>&gt;</span> </span><br><span class="line">    <span class="tag">&lt;/<span class="title">attribute</span>&gt;</span> </span><br><span class="line">    <span class="comment">&lt;!-- 配置标签属性:pass --&gt;</span> </span><br><span class="line">    <span class="tag">&lt;<span class="title">attribute</span>&gt;</span> </span><br><span class="line">        <span class="tag">&lt;<span class="title">name</span>&gt;</span>pass<span class="tag">&lt;/<span class="title">name</span>&gt;</span> </span><br><span class="line">        <span class="tag">&lt;<span class="title">required</span>&gt;</span>true<span class="tag">&lt;/<span class="title">required</span>&gt;</span> </span><br><span class="line">        <span class="tag">&lt;<span class="title">fragment</span>&gt;</span>true<span class="tag">&lt;/<span class="title">fragment</span>&gt;</span> </span><br><span class="line">    <span class="tag">&lt;/<span class="title">attribute</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">tag</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>JSTL是Sun提供的一套标签库，这套标签库的功能非常强大。另外，DisplayTag是Apache组织下的一套开源标签库，主要用于生成页面并显示效果。</p>
<h3 id="带标签体的标签">带标签体的标签</h3><p>带标签体的标签，可以在标签内嵌入其他内容（包括静态的HTML内容和动态的JSP内容），通常用于完成一些逻辑运算，例如判断和循环等。下面以一个迭代器标签为示例，介绍带标签体标签的开发过程。</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">IteratorTag</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">SimpleTagSupport</span>  &#123;</span></span><br><span class="line">    <span class="comment">//标签属性，用于指定需要被迭代的集合</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">String</span> collection;</span><br><span class="line">    <span class="comment">//标签属性，指定迭代集合元素，为集合元素指定的名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">String</span> item;</span><br><span class="line">    <span class="comment">//省略collection属性的setter和getter方法      ...      </span></span><br><span class="line">    <span class="comment">//省略item属性的setter和getter方法      ...      </span></span><br><span class="line">    <span class="comment">//标签的处理方法，简单标签处理类只需要重写doTag方法      </span></span><br><span class="line">    public void doTag() <span class="keyword">throws</span> <span class="type">JspException</span>, <span class="type">IOException</span>&#123;</span><br><span class="line">        <span class="comment">//从page scope中获取属性名为collection的集合</span></span><br><span class="line">        <span class="type">Collection</span> itemList = (<span class="type">Collection</span>)getJspContext().getAttribute(collection);</span><br><span class="line">        <span class="comment">//遍历集合          </span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">Object</span> s : itemList)</span><br><span class="line">        &#123; </span><br><span class="line">            <span class="comment">//将集合的元素设置到page 范围</span></span><br><span class="line">            getJspContext().setAttribute(item, s );</span><br><span class="line">            <span class="comment">//输出标签体              </span></span><br><span class="line">            getJspBody().invoke(<span class="literal">null</span>);</span><br><span class="line">        &#125;      </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>标签处理类的doTag方法首先从page范围内获取了指定名称的Collection对象，然后遍历Collection对象的元素，每次遍历都调用了getJspBody()方法，该方法返回该标签所包含的标签体：JspFragment对象，执行该对象的invoke()方法，即可输出标签体内容。该标签的作用是：遍历指定集合，每遍历一个集合元素，即输出标签体一次。</p>
<p>mytaglib.tld:<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">tag</span>&gt;</span>     </span><br><span class="line"><span class="comment">&lt;!-- 定义标签名 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">name</span>&gt;</span>iterator<span class="tag">&lt;/<span class="title">name</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 定义标签处理类 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">tag-class</span>&gt;</span>lee.IteratorTag<span class="tag">&lt;/<span class="title">tag-class</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 定义标签体不允许出现JSP脚本 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">body-content</span>&gt;</span>scriptless<span class="tag">&lt;/<span class="title">body-content</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 配置标签属性:collection --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">attribute</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">name</span>&gt;</span>collection<span class="tag">&lt;/<span class="title">name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">required</span>&gt;</span>true<span class="tag">&lt;/<span class="title">required</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">fragment</span>&gt;</span>true<span class="tag">&lt;/<span class="title">fragment</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">attribute</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 配置标签属性:item --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">attribute</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">name</span>&gt;</span>item<span class="tag">&lt;/<span class="title">name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">required</span>&gt;</span>true<span class="tag">&lt;/<span class="title">required</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">fragment</span>&gt;</span>true<span class="tag">&lt;/<span class="title">fragment</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">attribute</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">tag</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>iteratorTag.jsp:<br><figure class="highlight vbscript-html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"></span><span class="vbscript">&lt;%@ page contentType=<span class="string">"text/html; charset=GBK"</span> language=<span class="string">"java"</span> errorPage=<span class="string">""</span> %&gt;</span><span class="xml"> </span><br><span class="line"></span><span class="vbscript">&lt;%@ page import=<span class="string">"java.util.*"</span>%&gt;</span><span class="xml"></span><br><span class="line"><span class="comment">&lt;!-- 导入标签库，指定mytag前缀的标签，由http://www.crazyit.org/mytaglib的标签库处理 --&gt;</span></span><br><span class="line"></span><span class="vbscript">&lt;%@ taglib uri=<span class="string">"http://www.crazyit.org/mytaglib"</span> prefix=<span class="string">"mytag"</span>%&gt;</span><span class="xml"></span><br><span class="line"><span class="doctype">&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">h2</span>&gt;</span>带标签体的标签-迭代器标签<span class="tag">&lt;/<span class="title">h2</span>&gt;</span><span class="tag">&lt;<span class="title">hr</span>/&gt;</span></span><br><span class="line"></span><span class="vbscript">&lt;%</span><br><span class="line">//创建一个List对象</span><br><span class="line">List&lt;<span class="built_in">String</span>&gt; a = <span class="keyword">new</span> ArrayList&lt;<span class="built_in">String</span>&gt;();</span><br><span class="line">a.add(<span class="string">"疯狂Java"</span>);</span><br><span class="line">a.add(<span class="string">"www.crazyit.org"</span>);</span><br><span class="line">a.add(<span class="string">"java"</span>);</span><br><span class="line">//将List对象放入page范围内</span><br><span class="line">pageContext.setAttribute(<span class="string">"a"</span> , a); </span><br><span class="line">%&gt;</span><span class="xml"></span><br><span class="line"><span class="tag">&lt;<span class="title">table</span> <span class="attribute">border</span>=<span class="value">"1"</span> <span class="attribute">bgcolor</span>=<span class="value">"#aaaadd"</span> <span class="attribute">width</span>=<span class="value">"300"</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 使用迭代器标签，对a集合进行迭代 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">mytag:iterator</span> <span class="attribute">collection</span>=<span class="value">"a"</span> <span class="attribute">item</span>=<span class="value">"item"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">tr</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">td</span>&gt;</span>$&#123;pageScope.item&#125;<span class="tag">&lt;/<span class="title">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">tr</span>&gt;</span>         </span><br><span class="line"><span class="tag">&lt;/<span class="title">mytag:iterator</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">table</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">body</span>&gt;</span></span></span><br></pre></td></tr></table></figure></p>
<h3 id="以页面片段作为属性的标签">以页面片段作为属性的标签</h3><p>JSP 2规范的自定义标签还允许直接将一段”页面片段”作为属性，这种方式给自定义标签提供了更大的灵活性。</p>
<p>以”页面片段”为属性的标签与普通标签区别并不大，只有两个简单的改变：</p>
<ul>
<li>标签处理类中定义类型为JspFragment的属性，该属性代表了”页面片段”。</li>
<li>使用标签库时，通过<code>&lt;jsp:attribute.../&gt;</code>动作指令为标签库属性指定值。</li>
</ul>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">FragmentTag</span> <span class="title">extends</span> <span class="title">SimpleTagSupport</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> JspFragment fragment;     </span><br><span class="line">    <span class="comment">//fragment属性的setter和getter方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setFragment</span>(<span class="params">JspFragment fragment</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.fragment = fragment;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> JspFragment <span class="title">getFragment</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.fragment;</span><br><span class="line">    &#125;</span><br><span class="line">    @<span class="function">Override</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doTag</span>(<span class="params"></span>) throws JspException, IOException </span>&#123;</span><br><span class="line">        JspWriter <span class="keyword">out</span> = getJspContext().getOut();</span><br><span class="line">        <span class="keyword">out</span>.println(<span class="string">"&lt;div style='padding:10px;border:1px solid black'&gt;"</span>);</span><br><span class="line">        <span class="keyword">out</span>.println(<span class="string">"&lt;h3&gt;下面是动态传入的JSP片段&lt;/h3&gt;"</span>);</span><br><span class="line">        <span class="comment">//调用、输出"页面片段"</span></span><br><span class="line">        fragment.invoke( <span class="keyword">null</span> );</span><br><span class="line">        <span class="keyword">out</span>.println(<span class="string">"&lt;/div"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>mytaglib.tld:<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">tag</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 定义标签名 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">name</span>&gt;</span>fragment<span class="tag">&lt;/<span class="title">name</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 定义标签处理类 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">tag-class</span>&gt;</span>lee.FragmentTag<span class="tag">&lt;/<span class="title">tag-class</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 指定该标签不支持标签体 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">body-content</span>&gt;</span>empty<span class="tag">&lt;/<span class="title">body-content</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 定义标签属性：fragment --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">attribute</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">name</span>&gt;</span>fragment<span class="tag">&lt;/<span class="title">name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">required</span>&gt;</span>true<span class="tag">&lt;/<span class="title">required</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">fragment</span>&gt;</span>true<span class="tag">&lt;/<span class="title">fragment</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">attribute</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">tag</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>fragmentTag.jsp:<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="title">h2</span>&gt;</span>下面显示的是自定义标签中的内容<span class="tag">&lt;/<span class="title">h2</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">mytag:fragment</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 使用jsp:attribute标签传入fragment参数 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">jsp:attribute</span> <span class="attribute">name</span>=<span class="value">"fragment"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 下面是动态的JSP页面片段 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">mytag:helloWorld</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">jsp:attribute</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">mytag:fragment</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">br</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">mytag:fragment</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">jsp:attribute</span> <span class="attribute">name</span>=<span class="value">"fragment"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 下面是动态的JSP页面片段 --&gt;</span></span><br><span class="line">        $&#123;pageContext.request.remoteAddr&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="title">jsp:attribute</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">mytag:fragment</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<h3 id="动态属性的标签">动态属性的标签</h3><p>前面介绍带属性标签时，那些标签的属性个数是确定的，属性名也是确定的，绝大部分情况下这种带属性的标签能处理得很好，但在某些特殊情况下，我们需要传入自定义标签的属性个数是不确定的，属性名也不确定，这就需要借助于动态属性的标签了。</p>
<p>动态属性标签比普通标签多了如下两个额外要求：</p>
<ul>
<li>标签处理类还需要实现DynamicAttributes接口。</li>
<li>配置标签时通过<code>&lt;dynamic-attributes.../&gt;</code>子元素指定该标签支持动态属性。</li>
</ul>
<p>DynaAttributesTag.java<br><figure class="highlight processing"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> class DynaAttributesTag extends SimpleTagSupport implements DynamicAttributes &#123;</span><br><span class="line">    <span class="comment">//保存每个属性名的集合</span></span><br><span class="line">    <span class="keyword">private</span> ArrayList&lt;<span class="keyword">String</span>&gt; keys = <span class="keyword">new</span> ArrayList&lt;<span class="keyword">String</span>&gt;();</span><br><span class="line">    <span class="comment">//保存每个属性值的集合</span></span><br><span class="line">    <span class="keyword">private</span> ArrayList&lt;<span class="keyword">Object</span>&gt; values = <span class="keyword">new</span> ArrayList&lt;<span class="keyword">Object</span>&gt;();</span><br><span class="line">    @Override</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> doTag() <span class="keyword">throws</span> JspException, IOException &#123;</span><br><span class="line">        JspWriter out = getJspContext().getOut();</span><br><span class="line">        <span class="comment">//此处只是简单地输出每个属性</span></span><br><span class="line">        out.<span class="built_in">println</span>(<span class="string">"&lt;ol&gt;"</span>);</span><br><span class="line">        <span class="keyword">for</span>( <span class="built_in">int</span> i = <span class="number">0</span>; i &lt; keys.<span class="built_in">size</span>(); i++ ) &#123;</span><br><span class="line">            <span class="keyword">String</span> <span class="variable">key</span> = keys.<span class="built_in">get</span>( i );</span><br><span class="line">            <span class="keyword">Object</span> value = values.<span class="built_in">get</span>( i );</span><br><span class="line">            out.<span class="built_in">println</span>( <span class="string">"&lt;li&gt;"</span> + <span class="variable">key</span> + <span class="string">" = "</span> + value + <span class="string">"&lt;/li&gt;"</span> );</span><br><span class="line">        &#125;</span><br><span class="line">        out.<span class="built_in">println</span>(<span class="string">"&lt;/ol&gt;"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    @Override</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> setDynamicAttribute( <span class="keyword">String</span> uri, <span class="keyword">String</span> localName, <span class="keyword">Object</span> value ) <span class="keyword">throws</span> JspException &#123;</span><br><span class="line">        <span class="comment">//添加属性名</span></span><br><span class="line">        keys.<span class="built_in">add</span>( localName );</span><br><span class="line">        <span class="comment">//添加属性值</span></span><br><span class="line">        values.<span class="built_in">add</span>( value );</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>mytaglib.tld</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 定义接受动态属性的标签 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">tag</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">name</span>&gt;</span>dynaAttr<span class="tag">&lt;/<span class="title">name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">tag-class</span>&gt;</span>lee.DynaAttributesTag<span class="tag">&lt;/<span class="title">tag-class</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">body-content</span>&gt;</span>empty<span class="tag">&lt;/<span class="title">body-content</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 指定支持动态属性 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">dynamic-attributes</span>&gt;</span>true<span class="tag">&lt;/<span class="title">dynamic-attributes</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">tag</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>dynaAttrTag.jsp</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 导入标签库，指定mytag前缀的标签，由http://www.crazyit.org/mytaglib的标签库处理 --&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="title">%@</span> <span class="attribute">taglib</span> <span class="attribute">uri</span>=<span class="value">"http://www.crazyit.org/mytaglib"</span> <span class="attribute">prefix</span>=<span class="value">"mytag"</span><span class="value">%</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">h2</span>&gt;</span>下面显示的是自定义标签中的内容<span class="tag">&lt;/<span class="title">h2</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">h4</span>&gt;</span>指定两个属性<span class="tag">&lt;/<span class="title">h4</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">mytag:dynaAttr</span> <span class="attribute">name</span>=<span class="value">"crazyit"</span> <span class="attribute">url</span>=<span class="value">"crazyit.org"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">br</span>/&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="title">h4</span>&gt;</span>指定四个属性<span class="tag">&lt;/<span class="title">h4</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">mytag:dynaAttr</span> 书名=<span class="value">"疯狂Java讲义"</span> 价格=<span class="value">"99.0"</span> 出版时间=<span class="value">"2008年"</span> 描述=<span class="value">"Java图书"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">br</span>/&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="Filter介绍">Filter介绍</h2><p>Filter可认为是Servlet的一种”加强版”，它主要用于对用户请求进行预处理，也可以对HttpServletResponse进行后处理，是个典型的处理链。Filter也可对用户请求生成响应，这一点与Servlet相同，但实际上很少会使用Filter向用户请求生成响应。使用Filter完整的流程是：Filter对用户请求进行预处理，接着将请求交给Servlet进行处理并生成响应，最后Filter再对服务器响应进行后处理。</p>
<p>Filter有如下几个用处。</p>
<ul>
<li>在HttpServletRequest到达Servlet之前，拦截客户的HttpServletRequest。</li>
<li>根据需要检查HttpServletRequest，也可以修改HttpServletRequest头和数据。</li>
<li>在HttpServletResponse到达客户端之前，拦截HttpServletResponse。</li>
<li>根据需要检查HttpServletResponse，也可以修改HttpServletResponse头和数据。</li>
</ul>
<p>Filter有如下几个种类。</p>
<ul>
<li>用户授权的Filter：Filter负责检查用户请求，根据请求过滤用户非法请求。</li>
<li>日志Filter：详细记录某些特殊的用户请求。</li>
<li>负责解码的Filter：包括对非标准编码的请求解码。</li>
<li>能改变XML内容的XSLT Filter等。</li>
<li>Filter可负责拦截多个请求或响应；一个请求或响应也可被多个Filter拦截。</li>
</ul>
<p>创建一个Filter只需两个步骤：</p>
<ul>
<li>创建Filter处理类。</li>
<li>web.xml文件中配置Filter。</li>
</ul>
<h3 id="创建Filter类">创建Filter类</h3><p>创建Filter必须实现javax.servlet.Filter接口，在该接口中定义了如下三个方法。</p>
<ul>
<li>void init（FilterConfig config）：用于完成Filter的初始化。</li>
<li>void destroy()：用于Filter销毁前，完成某些资源的回收。</li>
<li>void doFilter（ServletRequest request，ServletResponse response,FilterChain chain）：实现过滤功能，该方法就是对每个请求及响应增加的额外处理。</li>
</ul>
<h3 id="配置Filter">配置Filter</h3><p>前面已经提到，Filter可以认为是Servlet的”增强版”，因此配置Filter与配置Servlet非常相似，都需要配置如下两个部分：</p>
<ul>
<li>配置Filter名。</li>
<li>配置Filter拦截URL模式。</li>
</ul>
<p>区别在于，Servlet通常只配置一个URL，而Filter可以同时拦截多个请求的URL。因此，在配置Filter的URL模式时通常会使用模式字符串，使得Filter可以拦截多个请求。与配置Servlet相似的是，配置Filter同样有两种方式：</p>
<ul>
<li>在Filter类中通过Annotation进行配置。</li>
<li>在web.xml文件中通过配置文件进行配置。</li>
</ul>
<p>@WebFilter(filterName=”log”, urlPatterns={“/*”})<br>@WebFilter修饰一个Filter类，用于对Filter进行配置，它支持如表所示的常用属性</p>
<p>@WebFilter支持的常用属性</p>
<p>属    性          | 是否必需 | 说    明<br>asyncSupported    | 否       | 指定该Filter是否支持异步操作模式。关于Filter的异步调用请参考2.15节<br>dispatcherTypes   | 否       | 指定该Filter仅对那种dispatcher模式的请求进行过滤。该属性支持ASYNC、ERROR、FORWARD、INCLUDE、REQUEST 这5个值的任意组合。默认值为同时过滤5种模式的请求<br>displayName       | 否       | 指定该Filter的显示名<br>filterName        |          | 指定该Filter的名称<br>initParams        | 否       | 用于为该Filter配置参数<br>servletNames      | 否       | 该属性值可指定多个Servlet的名称，用于指定该Filter仅对这几个Servlet执行过滤<br>urlPatterns/value | 否       | 这两个属性的作用完全相同。都指定该Filter所拦截的URL</p>
<p>在web.xml文件中配置Filter与配置Servlet非常相似，需要为Filter指定它所过滤的URL，并且也可以为Filter配置参数。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 定义Filter --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">filter</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- Filter的名字，相当于指定@WebFilter的filterName属性 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">filter-name</span>&gt;</span>log<span class="tag">&lt;/<span class="title">filter-name</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- Filter的实现类 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">filter-class</span>&gt;</span>lee.LogFilter<span class="tag">&lt;/<span class="title">filter-class</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">filter</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 定义Filter拦截的URL地址 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">filter-mapping</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- Filter的名字 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">filter-name</span>&gt;</span>log<span class="tag">&lt;/<span class="title">filter-name</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- Filter负责拦截的URL，相当于指定@WebFilter的urlPatterns属性 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">url-pattern</span>&gt;</span>/*<span class="tag">&lt;/<span class="title">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">filter-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>实际上Filter和Servlet极其相似，区别只是Filter的doFilter()方法里多了一个FilterChain的参数，通过该参数可以控制是否放行用户请求。</p>
<p>假设系统有包含多个Servlet，这些Servlet都需要进行一些的通用处理：比如权限控制、记录日志等，这将导致在这些Servlet的service方法中有部分代码是相同的—为了解决这种代码重复的问题，我们可以考虑把这些通用处理提取到Filter中完成，这样各Servlet中剩下的只是特定请求相关的处理代码，而通用处理则交给Filter完成。</p>
<p>由于Filter和Servlet如此相似，所以Filter和Servlet具有完全相同的生命周期行为，且Filter也可以通过<init-param...>元素或@WebFilter的initParams属性来配置初始化参数，获取Filter的初始化参数则使用FilterConfig的getInitParameter()方法。</init-param...></p>
<p>对于Java Web应用来说，要实现伪静态非常简单：可以通过Filter拦截所有发向<em>.html请求，然后按某种规则将请求forward到实际的</em>.jsp页面即可。现有的URL Rewrite开源项目为这种思路提供了实现，使用URL Rewrite实现网站伪静态也很简单。</p>
<p>下载URL Rewrite应下载其src项（urlrewritefilter-3.2.0-src.zip），下载完成后得到一个urlrewritefilter-3.2.0-src.zip文件，将该压缩文件解压缩，得到如下文件结构。</p>
<ul>
<li>api：该路径下存放了URL Rewrite项目的API文档。</li>
<li>lib：该路径下存放了URL Rewrite项目的编译和运行所需的第三方类库。</li>
<li>manual：该路径下存放了URL Rewrite项目使用手册。</li>
<li>src：该路径下存放了URL Rewrite项目的源代码。</li>
<li>webapp：该路径是一个URL Rewrite的示例应用。</li>
<li>LICENSE.txt等杂项文档。</li>
</ul>
<p>web.xml<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 配置Url Rewrite的Filter --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">filter</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">filter-name</span>&gt;</span>UrlRewriteFilter<span class="tag">&lt;/<span class="title">filter-name</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">filter-class</span>&gt;</span>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter<span class="tag">&lt;/<span class="title">filter-class</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">filter</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 配置Url Rewrite的Filter拦截所有请求 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">filter-mapping</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">filter-name</span>&gt;</span>UrlRewriteFilter<span class="tag">&lt;/<span class="title">filter-name</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">url-pattern</span>&gt;</span>/*<span class="tag">&lt;/<span class="title">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">filter-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>上面的配置片段指定使用URL Rewrite Filter拦截所有的用户请求。</p>
<p>在应用的WEB-INF路径下增加urlrewrite.xml文件，该文件定义了伪静态映射规则，这份伪静态规则是基于正则表达式的。</p>
<p>下面是本应用所使用的urlrewrite.xml伪静态规则文件。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="GBK"?&gt;</span></span><br><span class="line"><span class="doctype">&lt;!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.2//EN" "http://tuckey.org/res/dtds/urlrewrite3.2.dtd"&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">urlrewrite</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">rule</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 所有配置如下正则表达式的请求 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">from</span>&gt;</span>/userinf-(\w*).html<span class="tag">&lt;/<span class="title">from</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 将被forward到如下JSP页面，其中$1代表上面第一个正则表达式所匹配的字符串 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">to</span> <span class="attribute">type</span>=<span class="value">"forward"</span>&gt;</span>/userinf.jsp?username=$1<span class="tag">&lt;/<span class="title">to</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">rule</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">urlrewrite</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>上面的规则文件中只定义了一个简单的规则：所有发向/userinf-(\w<em>).html的请求都将被forward到user.jsp页面，并将(\w</em>)正则表达式所匹配的内容作为username参数值。根据这个伪静态规则，我们应该为该应用提供一个userinf.jsp页面，该页面只是一个模拟了一个显示用户信息的页面</p>
<p>userinf.jsp</p>
<figure class="highlight vbscript-html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"></span><span class="vbscript">&lt;%@ page contentType=<span class="string">"text/html; charset=GBK"</span> language=<span class="string">"java"</span> errorPage=<span class="string">""</span> %&gt;</span><span class="xml"></span><br><span class="line"></span><span class="vbscript">&lt;%</span><br><span class="line">//获取请求参数</span><br><span class="line"><span class="built_in">String</span> user = <span class="built_in">request</span>.getParameter(<span class="string">"username"</span>);</span><br><span class="line">%&gt;</span><span class="xml"></span><br><span class="line"><span class="doctype">&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">html</span> <span class="attribute">xmlns</span>=<span class="value">"http://www.w3.org/1999/xhtml"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">head</span>&gt;</span><span class="tag">&lt;<span class="title">title</span>&gt;</span> </span><span class="vbscript">&lt;%=user%&gt;</span><span class="xml">的个人信息 <span class="tag">&lt;/<span class="title">title</span>&gt;</span><span class="tag">&lt;/<span class="title">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">body</span>&gt;</span></span><br><span class="line"></span><span class="vbscript">&lt;%</span><br><span class="line">//此处应该通过数据库读取该用户对应的信息</span><br><span class="line">//此处只是模拟，因此简单输出：</span><br><span class="line">out.println(<span class="string">"现在时间是："</span> + <span class="keyword">new</span> java.util.<span class="built_in">Date</span>() + <span class="string">"&lt;br/&gt;"</span>);</span><br><span class="line">out.println(<span class="string">"用户名："</span> + user);  %&gt;</span><span class="xml"></span><br><span class="line"><span class="tag">&lt;/<span class="title">body</span>&gt;</span> <span class="tag">&lt;/<span class="title">html</span>&gt;</span></span></span><br></pre></td></tr></table></figure>
<h2 id="Listener_介绍">Listener 介绍</h2><p>当Web应用在Web容器中运行时，Web应用内部会不断地发生各种事件：如Web应用被启动、Web应用被停止，用户session开始、用户session结束、用户请求到达等，通常来说，这些Web事件对开发者是透明的。</p>
<p>实际上，Servlet API提供了大量监听器来监听Web应用的内部事件，从而允许当Web内部事件发生时回调事件监听器内的方法。</p>
<p>使用Listener只需要两个步骤：</p>
<ul>
<li>定义Listener实现类。</li>
<li>通过Annotation或在web.xml文件中配置Listerner。</li>
</ul>
<h3 id="实现Listenner类">实现Listenner类</h3><p>常用的Web事件监听器接口有如下几个。</p>
<ul>
<li>ServletContextListener：用于监听Web应用的启动和关闭。</li>
<li>ServletContextAttributeListener：用于监听ServletContext范围（application）内属性的改变。</li>
<li>ServletRequestListener：用于监听用户请求。</li>
<li>ServletRequestAttributeListener：用于监听ServletRequest范围（request）内属性的改变。</li>
<li>HttpSessionListener：用于监听用户session的开始和结束。</li>
<li>HttpSessionAttributeListener：用于监听HttpSession范围（session）内属性的改变。</li>
</ul>
<p>下面先以ServletContextListener为例来介绍Listener的开发和使用，ServletContextListener用于监听Web应用的启动和关闭。该Listener类必须实现ServletContextListener接口，该接口包含如下两个方法。</p>
<ul>
<li>contextInitialized(ServletContextEvent sce)：启动Web应用时，系统调用Listener的该方法。</li>
<li>contextDestroyed(ServletContextEvent sce)：关闭Web应用时，系统调用Listener的该方法。</li>
</ul>
<h3 id="配置Listener">配置Listener</h3><p>为Web应用配置Listener也有两种方式：</p>
<ul>
<li>使用@WebListener修饰Listener实现类即可。</li>
<li>在web.xml文档中使用<listener...>元素进行配置。</listener...></li>
</ul>
<p>在web.xml中使用<listener...>元素进行配置时只要配置如下子元素即可。<br>listener-class：指定Listener实现类。</listener...></p>
<p>使用ServletContextAttributeListener</p>
<p>ServletContextAttributeListener用于监听ServletContext（application）范围内属性的变化，实现该接口的监听器需要实现如下三个方法。</p>
<ul>
<li>attributeAdded(ServletContextAttributeEvent event)：当程序把一个属性存入application范围时触发该方法。</li>
<li>attributeRemoved(ServletContextAttributeEvent event)：当程序把一个属性从application范围删除时触发该方法。</li>
<li>attributeReplaced(ServletContextAttributeEvent event)：当程序替换application范围内的属性时将触发该方法。</li>
</ul>
<h3 id="使用ServletRequestListener和ServletRequestAttributeListener">使用ServletRequestListener和ServletRequestAttributeListener</h3><p>ServletRequestListener用于监听用户请求的到达，实现该接口的监听器需要实现如下两个方法。</p>
<ul>
<li>requestInitialized(ServletRequestEvent sre)：用户请求到底、被初始化时触发该方法。</li>
<li>requestDestroyed(ServletRequestEvent sre)：用户请求结束、被销毁时触发该方法。</li>
</ul>
<p>ServletRequestAttributeListener则用于监听ServletRequest（request）范围内属性的变化，实现该接口的监听器需要实现attributeAdded、attributeRemoved、attributeReplaced三个方法。</p>
<h3 id="使用HttpSessionListener和HttpSessionAttributeListener">使用HttpSessionListener和HttpSessionAttributeListener</h3><p>HttpSessionListener用于监听用户session的创建和销毁，实现该接口的监听器需要实现如下两个方法。</p>
<ul>
<li>sessionCreated(HttpSessionEvent se)：用户与服务器的会话开始、创建时时触发该方法。</li>
<li>sessionDestroyed(HttpSessionEvent se)：用户与服务器的会话断开、销毁时触发该方法。</li>
</ul>
<p>HttpSessionAttributeListener则用于监听HttpSession（session）范围内属性的变化，实现该接口的监听器需要实现attributeAdded、attributeRemoved、attributeReplaced三个方法。</p>
<h2 id="JSP_2特性">JSP 2特性</h2><p>相比JSP 1.2，JSP 2主要增加了如下新特性。</p>
<ul>
<li>直接配置JSP属性。</li>
<li>表达式语言。</li>
<li>简化的自定义标签API。</li>
<li>Tag文件语法。</li>
</ul>
<p>如果需要使用JSP 2语法，其web.xml文件必须使用Servlet 2.4以上版本的配置文件。Servlet 2.4以上版本的配置文件的根元素写法如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="GBK"?&gt;</span></span><br><span class="line"><span class="comment">&lt;!--  不再使用DTD，而是使用Schema描述，版本也升级为 2.4--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">web-app</span> <span class="attribute">xmlns</span>=<span class="value">"http://java.sun.com/xml/ns/j2ee"</span> </span><br><span class="line"><span class="attribute">xmlns:xsi</span>=<span class="value">"http://www.w3.org/2001/XMLSchema-instance"</span></span><br><span class="line"><span class="attribute">xsi:schemaLocation</span>=<span class="value">"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"</span> <span class="attribute">version</span>=<span class="value">"2.4"</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 此处是Web应用的其他配置 --&gt;</span></span><br><span class="line">...</span><br><span class="line"><span class="tag">&lt;/<span class="title">web-app</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="配置jsp属性">配置jsp属性</h3><p>JSP属性定义使用元素配置，主要包括如下4个方面。</p>
<ul>
<li>是否允许使用表达式语言：使用元素确定，默认值为false，即允许使用表达式语言。</li>
<li>是否允许使用JSP脚本：使用元素确定，默认值为false，即允许使用JSP脚本。</li>
<li>声明JSP页面的编码：使用元素确定，配置该元素后，可以代替每个页面里page指令contentType属性的charset部分。</li>
<li>使用隐式包含：使用和元素确定，可以代替在每个页面里使用include编译指令来包含其他页面。</li>
</ul>
<p>此处隐式包含的作用与JSP提供的静态包含的作用相似。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="GBK"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">web-app</span> <span class="attribute">xmlns</span>=<span class="value">"http://java.sun.com/xml/ns/javaee"</span></span><br><span class="line"><span class="attribute">xmlns:xsi</span>=<span class="value">"http://www.w3.org/2001/XMLSchema-instance"</span></span><br><span class="line"><span class="attribute">xsi:schemaLocation</span>=<span class="value">"http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"</span> <span class="attribute">version</span>=<span class="value">"3.0"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">jsp-config</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">jsp-property-group</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">url-pattern</span>&gt;</span>/noscript/*<span class="tag">&lt;/<span class="title">url-pattern</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">el-ignored</span>&gt;</span>true<span class="tag">&lt;/<span class="title">el-ignored</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">page-encoding</span>&gt;</span>GBK<span class="tag">&lt;/<span class="title">page-encoding</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">scripting-invalid</span>&gt;</span>true<span class="tag">&lt;/<span class="title">scripting-invalid</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">include-prelude</span>&gt;</span>/inc/top.jspf<span class="tag">&lt;/<span class="title">include-prelude</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">include-coda</span>&gt;</span>/inc/bottom.jspf<span class="tag">&lt;/<span class="title">include-coda</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">jsp-property-group</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">jsp-property-group</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">url-pattern</span>&gt;</span>*.jsp<span class="tag">&lt;/<span class="title">url-pattern</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">el-ignored</span>&gt;</span>false<span class="tag">&lt;/<span class="title">el-ignored</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">page-encoding</span>&gt;</span>GBK<span class="tag">&lt;/<span class="title">page-encoding</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">scripting-invalid</span>&gt;</span>false<span class="tag">&lt;/<span class="title">scripting-invalid</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">jsp-property-group</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">jsp-property-group</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">url-pattern</span>&gt;</span>/inc/*<span class="tag">&lt;/<span class="title">url-pattern</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">el-ignored</span>&gt;</span>false<span class="tag">&lt;/<span class="title">el-ignored</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">page-encoding</span>&gt;</span>GBK<span class="tag">&lt;/<span class="title">page-encoding</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="title">scripting-invalid</span>&gt;</span>true<span class="tag">&lt;/<span class="title">scripting-invalid</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="title">jsp-property-group</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">jsp-config</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">web-app</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="表达式语言">表达式语言</h3><p>表达式语言（Expression Language）是一种简化的数据访问方式。使用表达式语言可以方便地访问JSP的隐含对象和JavaBeans组件，在JSP 2规范中，建议尽量使用表达式语言使JSP文件的格式一致，避免使用Java脚本。</p>
<p>表达式语言的语法格式是： <code>${expression}</code><br>如果想输出<code>$</code>符号，则在<code>$</code>前加转义字符<code>\</code></p>
<ol>
<li><p>表达式语言支持的算术运算符和逻辑运算符</p>
<p> 所有java语言里的算术运算符都支持，甚至java不支持的运算符也支持。<br> div(除)、mod(取余)、lt(小于)、gt(大于)、ge(大于等于)、le(小于等于)、eq(等于)、ne(不等于)<br> 表达式语言不仅可在数字与数字之间比较，还可在字符与字符之间比较，字符串的比较是根据其对应UNICODE值来比较大小的。<br> 表达式语言把所有数值都当成浮点数处理，所以3/0的实质是3.0/0.0，得到结果应该是Infinity。</p>
</li>
<li><p>表达式语言的内置对象</p>
<p> 表达式语言包含如下11个内置对象。</p>
<ul>
<li>pageContext：代表该页面的pageContext对象，与JSP的pageContext内置对象相同。</li>
<li>pageScope：用于获取page范围的属性值。</li>
<li>requestScope：用于获取request范围的属性值。</li>
<li>sessionScope：用于获取session范围的属性值。</li>
<li>applicationScope：用于获取application范围的属性值。</li>
<li>param：用于获取请求的参数值。</li>
<li>paramValues：用于获取请求的参数值，与param的区别在于，该对象用于获取属性值为数组的属性值。</li>
<li>header：用于获取请求头的属性值。</li>
<li>headerValues：用于获取请求头的属性值，与header的区别在于，该对象用于获取属性值为数组的属性值。</li>
<li>initParam：用于获取请求Web应用的初始化参数。</li>
<li>cookie：用于获取指定的Cookie值。<br>两种方法取得请求参数值：<br><code>${param.name}</code>、 <code>${param[&quot;name&quot;]</code></li>
</ul>
</li>
<li><p>表达式语言的自定义函数</p>
<p> 表达式语言除了可以使用基本的运算符外，还可以使用自定义函数。通过自定义函数，能够大大加强表达式语言的功能。自定义函数的开发步骤非常类似于标签的开发步骤，定义方式也几乎一样。区别在于自定义标签直接在页面上生成输出，而自定义函数则需要在表达式语言中使用。</p>
<p> 函数功能大大扩充了EL的功能，EL本身只是一种数据访问语言，因此它不支持调用方法。如果需要在EL中进行更复杂的处理，就可以通过函数来完成。函数的本质是：提供一种语法允许在EL中调用某个类的静态方法。</p>
<p> 使用标签库定义函数：定义函数的方法与定义标签的方法大致相似。在<code>&lt;taglib.../&gt;</code>元素下增加<code>&lt;tag.../&gt;</code>元素用于定义自定义标签；增加<code>&lt;function.../&gt;</code>元素则用于定义自定义函数。每个<code>&lt;function.../&gt;</code>元素只要三个子元素即可。</p>
<ul>
<li>name：指定自定义函数的函数名。</li>
<li>function-class：指定自定义函数的处理类。</li>
<li><p>function-signature：指定自定义函数对应的方法。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="GBK"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">taglib</span> <span class="attribute">xmlns</span>=<span class="value">"http://java.sun.com/xml/ns/j2ee"</span></span><br><span class="line"><span class="attribute">xmlns:xsi</span>=<span class="value">"http://www.w3.org/2001/XMLSchema-instance"</span></span><br><span class="line"><span class="attribute">xsi:schemaLocation</span>=<span class="value">"http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd"</span> <span class="attribute">version</span>=<span class="value">"2.0"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">tlib-version</span>&gt;</span>1.0<span class="tag">&lt;/<span class="title">tlib-version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">short-name</span>&gt;</span>crazyit<span class="tag">&lt;/<span class="title">short-name</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 定义该标签库的URI --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">uri</span>&gt;</span>http://www.crazyit.org/tags<span class="tag">&lt;/<span class="title">uri</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 定义第一个函数 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">function</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 定义函数名:reverse --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">name</span>&gt;</span>reverse<span class="tag">&lt;/<span class="title">name</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 定义函数的处理类 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">function-class</span>&gt;</span>lee.Functions<span class="tag">&lt;/<span class="title">function-class</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 定义函数的实现方法--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">function-signature</span>&gt;</span>java.lang.String reverse(java.lang.String)<span class="tag">&lt;/<span class="title">function-signature</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">function</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 定义第二个函数: countChar --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">function</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 定义函数名:countChar --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">name</span>&gt;</span>countChar<span class="tag">&lt;/<span class="title">name</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 定义函数的处理类 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">function-class</span>&gt;</span>lee.Functions<span class="tag">&lt;/<span class="title">function-class</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 定义函数的实现方法--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="title">function-signature</span>&gt;</span>int countChar(java.lang.String)<span class="tag">&lt;/<span class="title">function-signature</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">function</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">taglib</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>上面的粗体字代码定义了两个函数，不难发现其实定义函数比定义自定义标签更简单，因为自定义函数只需配置三个子元素即可，变化更少。</p>
<p>useFunctions.jsp：</p>
<figure class="highlight dust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"><span class="tag">&lt;<span class="title">%@</span> <span class="attribute">page</span> <span class="attribute">contentType</span>=<span class="value">"text/html; charset=GBK"</span> <span class="attribute">language</span>=<span class="value">"java"</span> <span class="attribute">errorPage</span>=<span class="value">""</span> %&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">%@</span> <span class="attribute">taglib</span> <span class="attribute">prefix</span>=<span class="value">"crazyit"</span> <span class="attribute">uri</span>=<span class="value">"http://www.crazyit.org/tags"</span><span class="value">%</span>&gt;</span></span><br><span class="line"><span class="doctype">&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">html</span> <span class="attribute">xmlns</span>=<span class="value">"http://www.w3.org/1999/xhtml"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">head</span>&gt;</span><span class="tag">&lt;<span class="title">title</span>&gt;</span>new document<span class="tag">&lt;/<span class="title">title</span>&gt;</span><span class="tag">&lt;/<span class="title">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">h2</span>&gt;</span>表达式语言 - 自定义函数<span class="tag">&lt;/<span class="title">h2</span>&gt;</span><span class="tag">&lt;<span class="title">hr</span>/&gt;</span></span><br><span class="line">请输入一个字符串：</span><br><span class="line"><span class="tag">&lt;<span class="title">form</span> <span class="attribute">action</span>=<span class="value">"useFunctions.jsp"</span> <span class="attribute">method</span>=<span class="value">"post"</span>&gt;</span></span><br><span class="line">字符串 = <span class="tag">&lt;<span class="title">input</span> <span class="attribute">type</span>=<span class="value">"text"</span> <span class="attribute">name</span>=<span class="value">"name"</span> <span class="attribute">value</span>=<span class="value">"$</span></span></span><span class="expression">&#123;<span class="variable">param</span>['<span class="variable">name</span>']&#125;</span><span class="xml"><span class="tag"><span class="value">"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">input</span> <span class="attribute">type</span>=<span class="value">"submit"</span>  <span class="attribute">value</span>=<span class="value">"提交"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">form</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">table</span> <span class="attribute">border</span>=<span class="value">"1"</span> <span class="attribute">bgcolor</span>=<span class="value">"aaaadd"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">tr</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">td</span>&gt;</span><span class="tag">&lt;<span class="title">b</span>&gt;</span>表达式语言<span class="tag">&lt;/<span class="title">b</span>&gt;</span><span class="tag">&lt;/<span class="title">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">td</span>&gt;</span><span class="tag">&lt;<span class="title">b</span>&gt;</span>计算结果<span class="tag">&lt;/<span class="title">b</span>&gt;</span><span class="tag">&lt;/<span class="title">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">tr</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">tr</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">td</span>&gt;</span>\$</span><span class="expression">&#123;<span class="variable">param</span>[<span class="string">"name"</span>]&#125;</span><span class="xml"><span class="tag">&lt;/<span class="title">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">td</span>&gt;</span>$</span><span class="expression">&#123;<span class="variable">param</span>[<span class="string">"name"</span>]&#125;</span><span class="xml">&amp;nbsp;<span class="tag">&lt;/<span class="title">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">tr</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--  使用reverse函数--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">tr</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">td</span>&gt;</span>\$</span><span class="expression">&#123;<span class="variable">crazyit</span>:<span class="variable">reverse</span>(<span class="variable">param</span>[<span class="string">"name"</span>])&#125;</span><span class="xml"><span class="tag">&lt;/<span class="title">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">td</span>&gt;</span>$</span><span class="expression">&#123;<span class="variable">crazyit</span>:<span class="variable">reverse</span>(<span class="variable">param</span>[<span class="string">"name"</span>])&#125;</span><span class="xml">&amp;nbsp;<span class="tag">&lt;/<span class="title">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">tr</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">tr</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">td</span>&gt;</span>\$</span><span class="expression">&#123;<span class="variable">crazyit</span>:<span class="variable">reverse</span>(<span class="variable">crazyit</span>:<span class="variable">reverse</span>(<span class="variable">param</span>[<span class="string">"name"</span>]))&#125;</span><span class="xml"><span class="tag">&lt;/<span class="title">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">td</span>&gt;</span>$</span><span class="expression">&#123;<span class="variable">crazyit</span>:<span class="variable">reverse</span>(<span class="variable">crazyit</span>:<span class="variable">reverse</span>(<span class="variable">param</span>[<span class="string">"name"</span>]))&#125;</span><span class="xml">&amp;nbsp;<span class="tag">&lt;/<span class="title">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">tr</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 使用countChar函数 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">tr</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">td</span>&gt;</span>\$</span><span class="expression">&#123;<span class="variable">crazyit</span>:<span class="variable">countChar</span>(<span class="variable">param</span>[<span class="string">"name"</span>])&#125;</span><span class="xml"><span class="tag">&lt;/<span class="title">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">td</span>&gt;</span>$</span><span class="expression">&#123;<span class="variable">crazyit</span>:<span class="variable">countChar</span>(<span class="variable">param</span>[<span class="string">"name"</span>])&#125;</span><span class="xml">&amp;nbsp;<span class="tag">&lt;/<span class="title">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">tr</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">table</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">body</span>&gt;</span> <span class="tag">&lt;/<span class="title">html</span>&gt;</span></span></span><br></pre></td></tr></table></figure>
<p>如上面程序中粗体字代码所示，导入标签库定义文件后（实质上也是函数库定义文件），就可以在表达式语言中使用函数定义库文件里定义的各函数了。</p>
</li>
</ul>
</li>
</ol>
<h3 id="Tag_File_支持">Tag File 支持</h3><p>建立Tag文件，在JSP所支持Tag File规范下，Tag File代理了标签处理类，它的格式类似于JSP文件。可以这样理解：如同JSP可以代替Servlet作为表现层一样，Tag File则可以代替标签处理类。</p>
<p>Tag File具有以下5个编译指令。</p>
<ul>
<li>taglib：作用与JSP文件中的taglib指令效果相同，用于导入其他标签库。</li>
<li>include：作用与JSP文件中的include指令效果相同，用于导入其他JSP或静态页面。</li>
<li>tag：作用类似于JSP文件中的page指令，有pageEncoding、body-content等属性，用于设置页面编码等属性。</li>
<li>attribute：用于设置自定义标签的属性，类似于自定义标签处理类中的标签属性。</li>
<li>variable：用于设置自定义标签的变量，这些变量将传给JSP页面使用。</li>
</ul>
<p>下面是迭代器标签的Tag File，这个Tag File的语法与JSP语法非常相似。</p>
<p>iterator.tag<br><figure class="highlight vbscript-html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"></span><span class="vbscript">&lt;%@ tag pageEncoding=<span class="string">"GBK"</span> import=<span class="string">"java.util.List"</span>%&gt;</span><span class="xml"></span><br><span class="line"><span class="comment">&lt;!-- 定义了4个标签属性 --&gt;</span></span><br><span class="line"></span><span class="vbscript">&lt;%@ attribute name=<span class="string">"bgColor"</span> %&gt;</span><span class="xml"></span><br><span class="line"></span><span class="vbscript">&lt;%@ attribute name=<span class="string">"cellColor"</span> %&gt;</span><span class="xml"></span><br><span class="line"></span><span class="vbscript">&lt;%@ attribute name=<span class="string">"title"</span> %&gt;</span><span class="xml"></span><br><span class="line"></span><span class="vbscript">&lt;%@ attribute name=<span class="string">"bean"</span> %&gt;</span><span class="xml"></span><br><span class="line"><span class="tag">&lt;<span class="title">table</span> <span class="attribute">border</span>=<span class="value">"1"</span> <span class="attribute">bgcolor</span>=<span class="value">"$&#123;bgColor&#125;"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">tr</span>&gt;</span> <span class="tag">&lt;<span class="title">td</span>&gt;</span><span class="tag">&lt;<span class="title">b</span>&gt;</span>$&#123;title&#125;<span class="tag">&lt;/<span class="title">b</span>&gt;</span><span class="tag">&lt;/<span class="title">td</span>&gt;</span> <span class="tag">&lt;/<span class="title">tr</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 取出request范围的a集合 --&gt;</span></span><br><span class="line"></span><span class="vbscript">&lt;%</span><br><span class="line">List&lt;<span class="built_in">String</span>&gt; list = (List&lt;<span class="built_in">String</span>&gt;) <span class="built_in">request</span>.getAttribute(<span class="string">"a"</span>);</span><br><span class="line">//遍历输出list集合的元素</span><br><span class="line"><span class="keyword">for</span> (Object ele : list)&#123;</span><br><span class="line">%&gt;</span><span class="xml"> </span><br><span class="line"><span class="tag">&lt;<span class="title">tr</span>&gt;</span> <span class="tag">&lt;<span class="title">td</span> <span class="attribute">bgcolor</span>=<span class="value">"$&#123;cellColor&#125;"</span>&gt;</span></span><span class="vbscript">&lt;%=ele%&gt;</span><span class="xml"> <span class="tag">&lt;/<span class="title">td</span>&gt;</span> <span class="tag">&lt;/<span class="title">tr</span>&gt;</span></span><br><span class="line"></span><span class="vbscript">&lt;%&#125;%&gt;</span><span class="xml"></span></span><br></pre></td></tr></table></figure></p>
<p>将该文件存在Web应用的某个路径下，这个路径相当于标签库的URI名。如将其放在/WEB-INF/tags下</p>
<p>在页面中使用自定义标签时，需要先导入标签库，再使用标签。使用Tag File标签与普通自定义标签的用法完全相同，只是在导入标签库时存在一些差异。由于此时的标签库没有URI，只有标签库路径。因此导入标签时，使用如下语法格式：</p>
<figure class="highlight gcode"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;<span class="preprocessor">%</span>@ taglib prefix=<span class="string">"tagPrefix"</span> tagdir=<span class="string">"path"</span> <span class="preprocessor">%</span>&gt;</span><br></pre></td></tr></table></figure>
<p>其中，prefix与之前的taglib指令的prefix属性完全相同，用于确定标签前缀；而tagdir标签库路径下存放很多Tag File，每个Tag File对应一个标签。</p>
<p>useTagFile.jsp</p>
<figure class="highlight vbscript-html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"></span><span class="vbscript">&lt;%@ page contentType=<span class="string">"text/html; charset=GBK"</span> language=<span class="string">"java"</span> errorPage=<span class="string">""</span> %&gt;</span><span class="xml"></span><br><span class="line"></span><span class="vbscript">&lt;%@ page import=<span class="string">"java.util.*"</span> %&gt;</span><span class="xml"></span><br><span class="line"></span><span class="vbscript">&lt;%@ taglib prefix=<span class="string">"tags"</span> tagdir=<span class="string">"/WEB-INF/tags"</span> %&gt;</span><span class="xml"></span><br><span class="line"><span class="doctype">&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">html</span> <span class="attribute">xmlns</span>=<span class="value">"http://www.w3.org/1999/xhtml"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">head</span>&gt;</span><span class="tag">&lt;<span class="title">title</span>&gt;</span>迭代器tag file<span class="tag">&lt;/<span class="title">title</span>&gt;</span><span class="tag">&lt;/<span class="title">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">h2</span>&gt;</span>迭代器tag file<span class="tag">&lt;/<span class="title">h2</span>&gt;</span></span><br><span class="line"></span><span class="vbscript">&lt;%</span><br><span class="line">//创建集合对象，用于测试Tag File所定义的标签</span><br><span class="line">List&lt;<span class="built_in">String</span>&gt; a = <span class="keyword">new</span> ArrayList&lt;<span class="built_in">String</span>&gt;();</span><br><span class="line">a.add(<span class="string">"hello"</span>);</span><br><span class="line">a.add(<span class="string">"world"</span>);</span><br><span class="line">a.add(<span class="string">"java"</span>);</span><br><span class="line">//将集合对象放入页面范围</span><br><span class="line"><span class="built_in">request</span>.setAttribute(<span class="string">"a"</span> , a);%&gt;</span><span class="xml"></span><br><span class="line">//使用自定义标签</span><br><span class="line"><span class="tag">&lt;<span class="title">tags:iterator</span> <span class="attribute">bgColor</span>=<span class="value">"#99dd99"</span> <span class="attribute">cellColor</span>=<span class="value">"#9999cc"</span> <span class="attribute">title</span>=<span class="value">"迭代器标签"</span> <span class="attribute">bean</span>=<span class="value">"a"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">body</span>&gt;</span> <span class="tag">&lt;/<span class="title">html</span>&gt;</span></span></span><br></pre></td></tr></table></figure>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;tags:<span class="keyword">iterator</span> bgColor=<span class="string">"#99dd99"</span> cellColor=<span class="string">"#9999cc"</span> title=<span class="string">"迭代器标签"</span> bean=<span class="string">"a"</span> /&gt;</span><br></pre></td></tr></table></figure>
<p>tags表明该标签使用/WEB-INF/tags路径下的Tag File来处理标签；<strong>而iterator是标签名，即使用WEB-INF/tags路径下的iterator.tag文件负责处理该标签</strong>。</p>
<p>Tag File是自定义标签的简化。事实上，就如同JSP文件会编译成Servlet一样，Tag File也会编译成标签处理类，自定义标签的后台依然由标签处理类完成，而这个过程由容器完成。打开Tomcat的work\Catalina\localhost\jsp2\org\apache\jsp\tag\web路径，即可看到iterator_tag.java、iterator_tag.class两个文件，这两个文件就是Tag File所对应的标签处理类。</p>
<p>通过查看iterator_tag.java文件的内容不难发现，Tag File中只有如下几个内置对象。</p>
<ul>
<li>request：与JSP脚本中的request对象对应。</li>
<li>response：与JSP脚本中的response对象对应。</li>
<li>session：与JSP脚本中的session对象对应。</li>
<li>application：与JSP脚本中的application对象对应。</li>
<li>config：与JSP脚本中的config对象对应。</li>
<li>out：与JSP脚本中的out对象对应。</li>
</ul>
<h2 id="Servlet_3-0新特性">Servlet 3.0新特性</h2><h3 id="Servlet_3-0的Annotation">Servlet 3.0的Annotation</h3><p>Servlet 3.0规范在javax.servlet.annotation包下提供了如下Annotation。</p>
<ul>
<li>@WebServlet：用于修饰一个Servlet类，用于部署Servlet类。</li>
<li>@WebInitParam：用于与@WebServlet或@WebFilter一起使用，为Servlet、Filter配置参数。</li>
<li>@WebListener：用于修饰Listener类，用于部署Listener类。</li>
<li>@WebFilter：用于修饰Filter类，用于部署Filter类。</li>
<li>@MultipartConfig：用于修饰Servlet，指定该Servlet将会负责处理multipart/form-data类型的请求（主要用于文件上传）。</li>
<li>@ServletSecurity：这是一个与JAAS有关的Annotation，修饰Servlet指定该Servlet的安全与授权控制。</li>
<li>@HttpConstraint：用于与@ServletSecurity一起使用，用于指定该Servlet的安全与授权控制。</li>
<li>@HttpMethodConstraint：用于与@ServletSecurity一起使用，用于指定该Servlet的安全与授权控制。</li>
</ul>
<h3 id="Servlet_3-0的Web模块支持">Servlet 3.0的Web模块支持</h3><p>Servlet 3.0规范不再要求所有Web组件（如Servlet、Listener、Filter等）都部署在web.xml文件中，而是允许采用”Web模块”来部署、管理它们。</p>
<p>一个Web模块通常对应于一个JAR包，这个JAR包有如下文件结构：</p>
<figure class="highlight gherkin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">&lt;webModule&gt;</span>.jar--这是Web模块的JAR包，可以改变</span><br><span class="line">|<span class="string">－META-INF</span><br><span class="line"></span>|<span class="string">   </span>|<span class="string">－web-fragment.xml</span><br><span class="line"></span>|<span class="string">－Web模块所用的类文件、资源文件等。</span></span><br></pre></td></tr></table></figure>
<p>从上面的文件结构可以看出，Web模块与普通JAR的最大区别在于需要在META-INF目录下添加一个web-fragment.xml文件，这个文件也被称为Web模块部署描述符。</p>
<p>web-fragment.xml文件与web.xml文件的作用、文档结构都基本相似，因为它们都用于部署、管理各种Web组件。只是web-fragment.xml用于部署、管理Web模块而已，但web-fragment.xml文件可以多指定如下两个元素。</p>
<p><code>&lt;name.../&gt;</code>：用于指定该Web模块的名称。<br><code>&lt;ordering.../&gt;</code>：用于指定加载该Web模块的相对顺序。</p>
<p>web-fragment.xml:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="GBK"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">web-fragment</span> <span class="attribute">xmlns</span>=<span class="value">"http://java.sun.com/xml/ns/javaee"</span></span><br><span class="line"><span class="attribute">xmlns:xsi</span>=<span class="value">"http://www.w3.org/2001/XMLSchema-instance"</span></span><br><span class="line"><span class="attribute">xsi:schemaLocation</span>=<span class="value">"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-fragment_3_0.xsd"</span> <span class="attribute">version</span>=<span class="value">"3.0"</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 指定该Web模块的唯一标识 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">name</span>&gt;</span>crazyit<span class="tag">&lt;/<span class="title">name</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">listener</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">listener-class</span>&gt;</span>lee.CrazyitListener<span class="tag">&lt;/<span class="title">listener-class</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">listener</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">ordering</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 用于配置该Web模块必须位于哪些模块之前加载 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">before</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 用于指定位于其他所有模块之前加载 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">others</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">before</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">ordering</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">web-fragment</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>另一个web-fragment.xml:<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="pi">&lt;?xml version="1.0" encoding="GBK"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">web-fragment</span> <span class="attribute">xmlns</span>=<span class="value">"http://java.sun.com/xml/ns/javaee"</span></span><br><span class="line"><span class="attribute">xmlns:xsi</span>=<span class="value">"http://www.w3.org/2001/XMLSchema-instance"</span></span><br><span class="line"><span class="attribute">xsi:schemaLocation</span>=<span class="value">"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-fragment_3_0.xsd"</span> <span class="attribute">version</span>=<span class="value">"3.0"</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 指定该Web模块的唯一标识 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">name</span>&gt;</span>leegang<span class="tag">&lt;/<span class="title">name</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 配置Listener --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">listener</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">listener-class</span>&gt;</span>lee.LeegangListener<span class="tag">&lt;/<span class="title">listener-class</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">listener</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">ordering</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 用于配置该Web模块必须位于哪些模块之后加载 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">after</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 此处可用多个name元素列出该模块必须位于这些模块之后加载 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">name</span>&gt;</span>crazyit<span class="tag">&lt;/<span class="title">name</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">after</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">ordering</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="title">web-fragment</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>先加载crazyit模块，再加载leegang模块。</p>
<p>Web应用除了可按web-fragment.xml文件中指定的加载顺序来加载Web模块之外，还可以通过web.xml文件指定各Web模块加载的绝对顺序。在web.xml文件中指定的加载顺序将会覆盖Web模块中web-fragment.xml文件所指定的加载顺序。</p>
<h3 id="Servlet_3-0提供的异步处理">Servlet 3.0提供的异步处理</h3><p>在以前的Servlet规范中，如果Servlet作为控制器调用了一个耗时的业务方法，那么Servlet必须等到业务方法完全返回之后才会生成响应，这将使得Servlet对业务方法的调用变成一种阻塞式的调用，因此效率比较低。</p>
<p>Servlet 3.0规范引入了异步处理来解决这个问题，异步处理允许Servlet重新发起一条新线程去调用耗时的业务方法，这样就可避免等待。</p>
<p>Servlet 3.0的异步处理是通过AsyncContext类来处理的，Servlet可通过ServletRequest的如下两个方法开启异步调用、创建AsyncContext对象：</p>
<ul>
<li>AsyncContext startAsync()</li>
<li>AsyncContext startAsync(ServletRequest, ServletResponse)</li>
</ul>
<p>重复调用上面的方法将得到同一个AsyncContext对象。AsyncContext对象代表异步处理的上下文，它提供了一些工具方法，可完成设置异步调用的超时时长，dispatch用于请求、启动后台线程、获取request、response对象等功能。</p>
<p>AsyncServlet.java:</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="annotation">@WebServlet</span>(urlPatterns=<span class="string">"/async"</span>,asyncSupported=<span class="literal">true</span>)</span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">AsyncServlet</span> <span class="keyword"><span class="keyword">extends</span></span> <span class="title">HttpServlet</span>  &#123;</span></span><br><span class="line"><span class="annotation">@Override</span></span><br><span class="line">public void doGet(<span class="type">HttpServletRequest</span> request, <span class="type">HttpServletResponse</span> response)</span><br><span class="line"><span class="keyword">throws</span> <span class="type">IOException</span>,<span class="type">ServletException</span> &#123;</span><br><span class="line">    response.setContentType(<span class="string">"text/html;charset=GBK"</span>);</span><br><span class="line">    <span class="type">PrintWriter</span> out = response.getWriter();</span><br><span class="line">    out.println(<span class="string">"&lt;title&gt;异步调用示例&lt;/title&gt;"</span>);</span><br><span class="line">    out.println(<span class="string">"进入Servlet的时间："</span> + <span class="keyword">new</span> java.util.<span class="type">Date</span>() + <span class="string">".&lt;br/&gt;"</span>);</span><br><span class="line">    out.flush();</span><br><span class="line">    <span class="comment">//创建AsyncContext，开始异步调用</span></span><br><span class="line">    <span class="type">AsyncContext</span> actx = request.startAsync();</span><br><span class="line">    <span class="comment">//设置异步调用的超时时长</span></span><br><span class="line">    actx.setTimeout(<span class="number">30</span>*<span class="number">1000</span>);</span><br><span class="line">    <span class="comment">//启动异步调用的线程</span></span><br><span class="line">    actx.start(<span class="keyword">new</span> <span class="type">Executor</span>(actx));</span><br><span class="line">    out.println(<span class="string">"结束Servlet的时间："</span> + <span class="keyword">new</span> java.util.<span class="type">Date</span>() + <span class="string">".&lt;br/&gt;"</span>);</span><br><span class="line">    out.flush();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>下面是线程执行体的代码。</p>
<p>Executor.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Executor</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> AsyncContext actx = <span class="keyword">null</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Executor</span><span class="params">(AsyncContext actx)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.actx = actx;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//等待5秒钟，以模拟业务方法的执行</span></span><br><span class="line">            Thread.sleep(<span class="number">5</span> * <span class="number">1000</span>);</span><br><span class="line">            ServletRequest request = actx.getRequest();</span><br><span class="line">            List&lt;String&gt; books = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">            books.add(<span class="string">"疯狂Java讲义"</span>);</span><br><span class="line">            books.add(<span class="string">"经典Java EE企业应用实战"</span>);</span><br><span class="line">            books.add(<span class="string">"疯狂XML讲义"</span>);</span><br><span class="line">            request.setAttribute(<span class="string">"books"</span> , books);</span><br><span class="line">            actx.dispatch(<span class="string">"/async.jsp"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span>(Exception e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>该线程执行体内让线程暂停5秒来模拟调用耗时的业务方法，最后调用AsyncContext的dispatch方法把请求dispatch到指定JSP页面。</p>
<p>被异步请求dispatch的目标页面需要指定session=”false”，表明该页面不会重新创建session。</p>
<p>async.jsp:</p>
<figure class="highlight vbscript-html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"></span><span class="vbscript">&lt;%@ page contentType=<span class="string">"text/html; charset=GBK"</span> language=<span class="string">"java"</span> session=<span class="string">"false"</span>%&gt;</span><span class="xml"></span><br><span class="line"></span><span class="vbscript">&lt;%@ taglib prefix=<span class="string">"c"</span> uri=<span class="string">"http://java.sun.com/jsp/jstl/core"</span> %&gt;</span><span class="xml"></span><br><span class="line"><span class="tag">&lt;<span class="title">ul</span>&gt;</span> <span class="tag">&lt;<span class="title">c:forEach</span> <span class="attribute">items</span>=<span class="value">"$&#123;books&#125;"</span> <span class="attribute">var</span>=<span class="value">"book"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="title">li</span>&gt;</span>$&#123;book&#125;<span class="tag">&lt;/<span class="title">li</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">c:forEach</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="title">ul</span>&gt;</span></span><br><span class="line"></span><span class="vbscript">&lt;%out.println(<span class="string">"业务调用结束的时间："</span> + <span class="keyword">new</span> java.util.<span class="built_in">Date</span>());</span><br><span class="line">//完成异步调用</span><br><span class="line"><span class="built_in">request</span>.getAsyncContext().complete();</span><br><span class="line">%&gt;</span><span class="xml"></span></span><br></pre></td></tr></table></figure>
<p>为Servlet开启异步调用有两种方式：</p>
<ul>
<li>为@WebServlet指定asyncSupported=true。</li>
<li>在web.xml文件的<servlet...>元素中增加<async-supported...>子元素。</async-supported...></servlet...></li>
</ul>
<p>当Servlet启用异步调用的线程之后，该线程的执行过程对开发者是透明的。但在有些情况下，开发者需要了解该异步线程的执行细节，并针对特定的执行结果进行针对性处理，这可借助于Servlet 3.0提供的异步监听器来实现。</p>
<p>异步监听器需要实现AsyncListener接口，实现该接口的监听器类需要实现如下4个方法。</p>
<ul>
<li>onStartAsync(AsyncEvent event)：当异步调用开始时触发该方法。</li>
<li>onComplete(AsyncEvent event)：当异步调用完成时触发该方法。</li>
<li>onError(AsyncEvent event)：当异步调用出错时触发该方法。</li>
<li>onTimeout(AsyncEvent event)：当异步调用超时时触发该方法。</li>
</ul>
<p>提供了异步监听器之后，还需要通过AsyncContext来注册监听器，调用该对象的addListener()方法即可注册监听器。例如在上面的Servlet中增加如下代码即可注册监听器：</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">AsyncContext actx = request.startAsync<span class="params">()</span>;</span><br><span class="line"><span class="comment">//为该异步调用注册监听器</span></span><br><span class="line">actx.addListener<span class="params">(new MyAsyncListener<span class="params">()</span>)</span>;</span><br></pre></td></tr></table></figure>
<p>虽然上面的MyAsyncListener监听器类可以监听异步调用开始、异步调用完成两个事件，但从实际运行的结果来看，它并不能监听到异步调用开始事件，这可能是因为注册该监听器时异步调用已经开始了的缘故。</p>
<p>在Filter中进行异步调用与在Servlet中进行异步调用的效果完全相似</p>
<h3 id="改进的Servlet_API">改进的Servlet API</h3><p>Servlet 3.0还有一个改变是改进了部分API，这种改进很好地简化了Java Web开发。其中两个较大的改进是：</p>
<p>HttpServletRequest增加了对文件上传的支持。</p>
<p>ServletContext允许通过编程的方式动态注册Servlet、Filter。</p>
<p>HttpServletRequest提供了如下两个方法来处理文件上传。</p>
<p>Part getPart(String name)：根据名称来获取文件上传域。</p>
<p>Collection<part> getParts()：获取所有的文件上传域。</part></p>
<p>上面两个方法的返回值都涉及一个API：Part，每个Part对象对应于一个文件上传域，该对象提供了大量方法来访问上传文件的文件类型、大小、输入流等，并提供了一个write(String file)方法将上传文件写入服务器磁盘。</p>
<p>为了向服务器上传文件，需要在表单里使用<code>&lt;input type=&quot;file&quot; .../&gt;</code>文件域，这个文件域会在HTML页面上产生一个单行文本框和一个”浏览”按钮，浏览者可通过该按钮选择需要上传的文件。除此之外，上传文件一定要为表单域设置enctype属性。</p>
<p>表单的enctype属性指定的是表单数据的编码方式，该属性有如下三个值。</p>
<ul>
<li>application/x-www-form-urlencoded：这是默认的编码方式，它只处理表单域里的value属性值，采用这种编码方式的表单会将表单域的值处理成URL编码方式。</li>
<li>multipart/form-data：这种编码方式会以二进制流的方式来处理表单数据，这种编码方式会把文件域指定文件的内容也封装到请求参数里。</li>
<li>text/plain：这种编码方式当表单的action属性为mailto:URL的形式时比较方便，这种方式主要适用于直接通过表单发送邮件的方式。</li>
</ul>
<p>如果将enctype设置为application/x-www-form-urlencoded，或不设置enctype属性，提交表单时只会发送文件域的文本框里的字符串，也就是浏览者所选择文件的绝对路径，对服务器获取该文件在客户端上的绝对路径没有任何作用，因为服务器不可能访问客户机的文件系统。</p>
<p>UploadServlet.java:</p>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">@WebServlet<span class="params">(name=<span class="string">"upload"</span> , urlPatterns=&#123;<span class="string">"/upload"</span>&#125;)</span></span><br><span class="line">@MultipartConfig</span><br><span class="line">public class UploadServlet extends HttpServlet &#123;</span><br><span class="line">    public void service<span class="params">(HttpServletRequest request , HttpServletResponse response)</span> throws IOException , ServletException &#123; </span><br><span class="line">        response.setContentType<span class="params">(<span class="string">"text/html;charset=GBK"</span>)</span>;</span><br><span class="line">        PrintWriter out = response.getWriter<span class="params">()</span>;</span><br><span class="line">        <span class="comment">//获取普通请求参数</span></span><br><span class="line">        String fileName = request.getParameter<span class="params">(<span class="string">"name"</span>)</span>;</span><br><span class="line">        <span class="comment">//获取文件上传域</span></span><br><span class="line">        Part part = request.getPart<span class="params">(<span class="string">"file"</span>)</span>;</span><br><span class="line">        <span class="comment">//获取上传文件的类型</span></span><br><span class="line">        out.println<span class="params">(<span class="string">"上传文件的类型为："</span> + part.getContentType<span class="params">()</span> + <span class="string">"&lt;br/&gt;"</span>)</span>;</span><br><span class="line">        <span class="comment">//获取上传文件的大小</span></span><br><span class="line">        out.println<span class="params">(<span class="string">"上传文件的的大小为："</span> + part.getSize<span class="params">()</span>  + <span class="string">"&lt;br/&gt;"</span>)</span>;</span><br><span class="line">        <span class="comment">//获取该文件上传域的Header Name</span></span><br><span class="line">        Collection&lt;String&gt; headerNames = part.getHeaderNames<span class="params">()</span>;</span><br><span class="line">        <span class="comment">//遍历文件上传域的Header Name、Value</span></span><br><span class="line">        <span class="keyword">for</span> <span class="params">(String headerName : headerNames)</span> &#123;</span><br><span class="line">            out.println<span class="params">(headerName + <span class="string">"---&gt;"</span> + part.getHeader<span class="params">(headerName)</span> + <span class="string">"&lt;br/&gt;"</span>)</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//将上传的文件写入服务器</span></span><br><span class="line">        part.write<span class="params">(getServletContext<span class="params">()</span>.getRealPath<span class="params">(<span class="string">"/uploadFiles"</span>)</span> + <span class="string">"/"</span> + fileName )</span>;</span><br><span class="line">        <span class="comment">//①</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面Servlet使用了@MultipartConfig修饰，处理文件上传的Servlet应该使用该Annotation修饰。接下来该Servlet中HttpServletRequest就可通过getPart(String name)方法来获取文件上传域—就像获取普通请求参数一样。</p>
<p>与Servlet 3.0所有Annotation相似的是，Servlet 3.0为@提供了相似的配置元素，我们同样可以通过在<servlet...>元素中添加<multipart-config...>子元素来达到相同的效果。</multipart-config...></servlet...></p>
<p>上面Servlet上传时保存的文件名直接使用了name请求参数，实际项目中一般不会这么做，因为可能多个用户会填写相同的name参数，这样将导致后面用户上传的文件覆盖前面用户上传的图片。实际项目中可借助于java.util.UUID工具类生成文件名。</p>
<p>ServletContext则提供了如下方法来动态地注册Servet、Filter，并允许动态设置Web应用的初始化参数。</p>
<ul>
<li>多个重载的addServlet：动态地注册Servlet。</li>
<li>多个重载的addFilter：动态地注册Filter。</li>
<li>多个重载的addListener：动态地注册Listener。</li>
</ul>
<p>setInitParameter(String name, String value)：为Web应用设置初始化参数。</p>

      
    </div>
    <footer class="article-footer">
	  
	  <!-- 百度分享 Start -->
	  <div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a><a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a><a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博"></a><a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网"></a><a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a></div>
	  <!-- 百度分享 End -->
	  
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JSP/">JSP</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Servlet/">Servlet</a></li></ul>

	  
<span>
Updated:<time datetime="2015-04-12T12:00:43.000Z" itemprop="dateModified">2015-04-12</time>
</span>


    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2015/04/07/jvm-note-1/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          深入理解Java虚拟机笔记一（Java内存区域与内存溢出异常）
        
      </div>
    </a>
  
  
    <a href="/2015/03/06/spring-note-1/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">Spring笔记一</div>
    </a>
  
</nav>

  
</article>



<!-- 多说评论框 start -->

<section id="comments">
  <div class="ds-thread"  data-thread-key="/2015/03/13/jsp-servlet-note/" data-title="JSP/Servlet及相关技术笔记" data-url="http://howiefh.github.io/2015/03/13/jsp-servlet-note/" id="ds_thread">
    <noscript>Please enable JavaScript to view the <a href="//duoshuo.com/?ref_noscript">comments powered by duoshuo.</a></noscript>
  </div>
</section>

<!-- 多说评论框 end -->
</section>
        
          
  <div id="toc" class="toc-aside">
  <h2 class="toc-title">Contents</h2>
    
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#web应用"><span class="toc-number">1.</span> <span class="toc-text">web应用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#java脚本"><span class="toc-number">2.</span> <span class="toc-text">java脚本</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jsp注释"><span class="toc-number">3.</span> <span class="toc-text">jsp注释</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jsp声明"><span class="toc-number">4.</span> <span class="toc-text">jsp声明</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#输出jsp表达式"><span class="toc-number">5.</span> <span class="toc-text">输出jsp表达式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jsp_3个编译指令"><span class="toc-number">6.</span> <span class="toc-text">jsp 3个编译指令</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#page指令"><span class="toc-number">6.1.</span> <span class="toc-text">page指令</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#include指令"><span class="toc-number">6.2.</span> <span class="toc-text">include指令</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jsp7个动作指令"><span class="toc-number">7.</span> <span class="toc-text">jsp7个动作指令</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#forward指令"><span class="toc-number">7.1.</span> <span class="toc-text">forward指令</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#include指令-1"><span class="toc-number">7.2.</span> <span class="toc-text">include指令</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#useBean、setProperty、getProperty指令"><span class="toc-number">7.3.</span> <span class="toc-text">useBean、setProperty、getProperty指令</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#param指令"><span class="toc-number">7.4.</span> <span class="toc-text">param指令</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jsp脚本中的9个内置对象"><span class="toc-number">8.</span> <span class="toc-text">jsp脚本中的9个内置对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#application"><span class="toc-number">8.1.</span> <span class="toc-text">application</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#config"><span class="toc-number">8.2.</span> <span class="toc-text">config</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#exception"><span class="toc-number">8.3.</span> <span class="toc-text">exception</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#out"><span class="toc-number">8.4.</span> <span class="toc-text">out</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#pageContext"><span class="toc-number">8.5.</span> <span class="toc-text">pageContext</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#request"><span class="toc-number">8.6.</span> <span class="toc-text">request</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#response"><span class="toc-number">8.7.</span> <span class="toc-text">response</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#session"><span class="toc-number">8.8.</span> <span class="toc-text">session</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#servlet介绍"><span class="toc-number">9.</span> <span class="toc-text">servlet介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Servlet的开发"><span class="toc-number">9.1.</span> <span class="toc-text">Servlet的开发</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#servlet的配置"><span class="toc-number">9.2.</span> <span class="toc-text">servlet的配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#JSP/Servlet的生命周期"><span class="toc-number">9.3.</span> <span class="toc-text">JSP/Servlet的生命周期</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#load-on-startup_Servlet"><span class="toc-number">9.4.</span> <span class="toc-text">load-on-startup Servlet</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#访问Servlet的配置参数"><span class="toc-number">9.5.</span> <span class="toc-text">访问Servlet的配置参数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用Servlet作为控制器"><span class="toc-number">9.6.</span> <span class="toc-text">使用Servlet作为控制器</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JSP_2的自定义标签"><span class="toc-number">10.</span> <span class="toc-text">JSP 2的自定义标签</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#开发自定义标签类"><span class="toc-number">10.1.</span> <span class="toc-text">开发自定义标签类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#建立TLD文件"><span class="toc-number">10.2.</span> <span class="toc-text">建立TLD文件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用标签库"><span class="toc-number">10.3.</span> <span class="toc-text">使用标签库</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#带属性的标签"><span class="toc-number">10.4.</span> <span class="toc-text">带属性的标签</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#带标签体的标签"><span class="toc-number">10.5.</span> <span class="toc-text">带标签体的标签</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#以页面片段作为属性的标签"><span class="toc-number">10.6.</span> <span class="toc-text">以页面片段作为属性的标签</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#动态属性的标签"><span class="toc-number">10.7.</span> <span class="toc-text">动态属性的标签</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Filter介绍"><span class="toc-number">11.</span> <span class="toc-text">Filter介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#创建Filter类"><span class="toc-number">11.1.</span> <span class="toc-text">创建Filter类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#配置Filter"><span class="toc-number">11.2.</span> <span class="toc-text">配置Filter</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Listener_介绍"><span class="toc-number">12.</span> <span class="toc-text">Listener 介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#实现Listenner类"><span class="toc-number">12.1.</span> <span class="toc-text">实现Listenner类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#配置Listener"><span class="toc-number">12.2.</span> <span class="toc-text">配置Listener</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用ServletRequestListener和ServletRequestAttributeListener"><span class="toc-number">12.3.</span> <span class="toc-text">使用ServletRequestListener和ServletRequestAttributeListener</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用HttpSessionListener和HttpSessionAttributeListener"><span class="toc-number">12.4.</span> <span class="toc-text">使用HttpSessionListener和HttpSessionAttributeListener</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JSP_2特性"><span class="toc-number">13.</span> <span class="toc-text">JSP 2特性</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#配置jsp属性"><span class="toc-number">13.1.</span> <span class="toc-text">配置jsp属性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#表达式语言"><span class="toc-number">13.2.</span> <span class="toc-text">表达式语言</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Tag_File_支持"><span class="toc-number">13.3.</span> <span class="toc-text">Tag File 支持</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Servlet_3-0新特性"><span class="toc-number">14.</span> <span class="toc-text">Servlet 3.0新特性</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Servlet_3-0的Annotation"><span class="toc-number">14.1.</span> <span class="toc-text">Servlet 3.0的Annotation</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Servlet_3-0的Web模块支持"><span class="toc-number">14.2.</span> <span class="toc-text">Servlet 3.0的Web模块支持</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Servlet_3-0提供的异步处理"><span class="toc-number">14.3.</span> <span class="toc-text">Servlet 3.0提供的异步处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#改进的Servlet_API"><span class="toc-number">14.4.</span> <span class="toc-text">改进的Servlet API</span></a></li></ol></li></ol>
    
  </div>

<aside id="sidebar">

  
    
<div class="widget-wrap">
  <h3 class="widget-title">ABOUT ME</h3>
  <ul class="widget about-me">
    
    <li><img class="author" title="About me" src="http://fh-1.qiniudn.com/okal-eltocat.jpg" /></li>
    
    
    <li>Hi,I'm FengHao.</li>
    
    <li>I'll share something interesting and my learning experience with you at this blog.</li>
    
    <li>前博客:<a href="http://hi.baidu.com/idea_star" target="_BLANK">百度空间</a></li>
    
  </ul>
</div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Categories</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Android/">Android</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/C/">C</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Database/">Database</a><span class="category-list-count">13</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/Database/MongoDB/">MongoDB</a><span class="category-list-count">10</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Database/MySQL/">MySQL</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/Eclipse/">Eclipse</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/FTP/">FTP</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Git/">Git</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Hexo/">Hexo</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Java/">Java</a><span class="category-list-count">20</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/Java/FreeMarker/">FreeMarker</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Java/Shiro/">Shiro</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/">JavaEE</a><span class="category-list-count">4</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/Hibernate/">Hibernate</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/JSP/">JSP</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/Spring/">Spring</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaScript/">JavaScript</a><span class="category-list-count">5</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/JavaScript/jQuery/">jQuery</a><span class="category-list-count">1</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/Linux/">Linux</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/PHP/">PHP</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Suse/">Suse</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Ubuntu/">Ubuntu</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Vim/">Vim</a><span class="category-list-count">8</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/编程/">编程</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/软件/">软件</a><span class="category-list-count">1</span></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/Android/" style="font-size: 14.75px; color: #65bfa7">Android</a> <a href="/tags/C/" style="font-size: 13.88px; color: #71c1c2">C</a> <a href="/tags/CAS/" style="font-size: 13px; color: #7dc3de">CAS</a> <a href="/tags/Chrome/" style="font-size: 13px; color: #7dc3de">Chrome</a> <a href="/tags/Clean-Code/" style="font-size: 13.88px; color: #71c1c2">Clean Code</a> <a href="/tags/Database/" style="font-size: 13px; color: #7dc3de">Database</a> <a href="/tags/Eclipse/" style="font-size: 13px; color: #7dc3de">Eclipse</a> <a href="/tags/FTP/" style="font-size: 13.88px; color: #71c1c2">FTP</a> <a href="/tags/FreeMarker/" style="font-size: 14.75px; color: #65bfa7">FreeMarker</a> <a href="/tags/Gcc/" style="font-size: 13px; color: #7dc3de">Gcc</a> <a href="/tags/Git/" style="font-size: 14.75px; color: #65bfa7">Git</a> <a href="/tags/Github-Pages/" style="font-size: 13px; color: #7dc3de">Github Pages</a> <a href="/tags/Hexo/" style="font-size: 14.75px; color: #65bfa7">Hexo</a> <a href="/tags/Hibernate/" style="font-size: 13px; color: #7dc3de">Hibernate</a> <a href="/tags/JSP/" style="font-size: 13px; color: #7dc3de">JSP</a> <a href="/tags/JVM/" style="font-size: 14.75px; color: #65bfa7">JVM</a> <a href="/tags/Java/" style="font-size: 14.75px; color: #65bfa7">Java</a> <a href="/tags/JavaMail/" style="font-size: 13px; color: #7dc3de">JavaMail</a> <a href="/tags/JavaScript/" style="font-size: 16.5px; color: #4dbc6f">JavaScript</a> <a href="/tags/Linux/" style="font-size: 13.88px; color: #71c1c2">Linux</a> <a href="/tags/Log/" style="font-size: 13px; color: #7dc3de">Log</a> <a href="/tags/Markdown/" style="font-size: 13.88px; color: #71c1c2">Markdown</a> <a href="/tags/MongoDB/" style="font-size: 20px; color: #1db400">MongoDB</a> <a href="/tags/MySQL/" style="font-size: 13.88px; color: #71c1c2">MySQL</a> <a href="/tags/PHP/" style="font-size: 16.5px; color: #4dbc6f">PHP</a> <a href="/tags/Rhythmbox/" style="font-size: 13px; color: #7dc3de">Rhythmbox</a> <a href="/tags/SSO/" style="font-size: 13px; color: #7dc3de">SSO</a> <a href="/tags/Servlet/" style="font-size: 13px; color: #7dc3de">Servlet</a> <a href="/tags/Shiro/" style="font-size: 13.88px; color: #71c1c2">Shiro</a> <a href="/tags/Spring/" style="font-size: 13.88px; color: #71c1c2">Spring</a> <a href="/tags/Suse/" style="font-size: 13px; color: #7dc3de">Suse</a> <a href="/tags/Thinking-in-Java/" style="font-size: 19.13px; color: #29b61c">Thinking in Java</a> <a href="/tags/Ubuntu/" style="font-size: 17.38px; color: #41ba53">Ubuntu</a> <a href="/tags/Vim/" style="font-size: 18.25px; color: #35b838">Vim</a> <a href="/tags/VirtualBox/" style="font-size: 13px; color: #7dc3de">VirtualBox</a> <a href="/tags/Vsftpd/" style="font-size: 13px; color: #7dc3de">Vsftpd</a> <a href="/tags/jQuery/" style="font-size: 13px; color: #7dc3de">jQuery</a> <a href="/tags/pam-mysql/" style="font-size: 13px; color: #7dc3de">pam_mysql</a> <a href="/tags/小米/" style="font-size: 13px; color: #7dc3de">小米</a> <a href="/tags/软件/" style="font-size: 15.63px; color: #59bd8b">软件</a>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/09/">September 2015</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/08/">August 2015</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/07/">July 2015</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/05/">May 2015</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/04/">April 2015</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/03/">March 2015</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/02/">February 2015</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/12/">December 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/11/">November 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/10/">October 2014</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/09/">September 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/08/">August 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/07/">July 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/06/">June 2014</a><span class="archive-list-count">6</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/05/">May 2014</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/04/">April 2014</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/03/">March 2014</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/02/">February 2014</a><span class="archive-list-count">11</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/01/">January 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/12/">December 2013</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/11/">November 2013</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/08/">August 2013</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/07/">July 2013</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/06/">June 2013</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/05/">May 2013</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/04/">April 2013</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/03/">March 2012</a><span class="archive-list-count">1</span></li></ul>
    </div>
  </div>


  
    <div class="widget-wrap">
  <h3 class="widget-title">Calendar</h3>
  <div class="widget">
    <div id="g-calendar" class="g-calendar">
        <span class="g-calendar-prev"></span>
		 
        <span class="g-calendar-back"></span>
        <span class="g-calendar-now"></span>
		 
        <span class="g-calendar-next"></span>
        <div class="g-calendar-hd"></div>
        <div class="g-calendar-tit"></div>
        <div class="g-calendar-bd"></div>
    </div>
  </div>
</div>
<script type="text/javascript">
function LGY_calendar(wrapId, options){
    this.oWrap = this.getId(wrapId);
    this.oHead = this.getByClassName('g-calendar-hd',this.oWrap)[0];
    this.oBody = this.getByClassName('g-calendar-bd',this.oWrap)[0];
    this.oTit = this.getByClassName('g-calendar-tit',this.oWrap)[0];
    this.oPrev = this.getByClassName('g-calendar-prev',this.oWrap)[0];
    this.oNext = this.getByClassName('g-calendar-next',this.oWrap)[0];
    this.oNow = this.getByClassName('g-calendar-now',this.oWrap)[0];
    this.oBack = this.getByClassName('g-calendar-back',this.oWrap)[0];
    this.init();
}
LGY_calendar.prototype = {
    ///////////获取ID元素
    getId:function(id){
        return document.getElementById(id);
    },
    ////////获取css类名元素
    getByClassName:function(className,parent){
        var elem = [],
            node = parent != undefined&&parent.nodeType==1?parent.getElementsByTagName('*'):document.getElementsByTagName('*'),
            p = new RegExp("(^|\\s)"+className+"(\\s|$)");
        for(var n=0,i=node.length;n<i;n++){
            if(p.test(node[n].className)){
                elem.push(node[n]);
            }
        }
        return elem;
    },
    //填充日历
    fillDate:function(year,month){
        //本月份第一天是星期几-为显示上个月的天数做铺垫
        var first_day = new Date(year,month,1).getDay(),
        //如果刚好是星期天，则空出一行（显示上个月的天数）
            first_day = first_day == 0?first_day=7:first_day;
        //本月份最后一天是几号
        var final_date = new Date(year,month+1,0).getDate(),
        //上个月的最后一天是几号
            last_date = new Date(year,month,0).getDate(),
        //剩余的格子数--即排在末尾的格子数
            surplus = 42 - first_day - final_date;
        //设置年的链接
        var yearHead = "<a href='/" + "archives/" + year + "/'>" + year + " "+ "</a>"; 
        //设置年的链接
        var monthHead = "";
        var month1 = month + 1;
        if (month1 < 10) {
            monthHead = "<a href='/" + "archives/" + year + "/" + "0" + month1 + "/'>" + " " + month1 + " " + "</a>";
        } else {
            monthHead = "<a href='/" + "archives/" + year + "/" + month1 + "/'>" + " " + month1 + " " + "</a>";
        }
        //设置表头的日历
        this.oHead.innerHTML = yearHead+'年'+monthHead+'月';
        //填充日历执行
        var html = '';
        //上个月的显示天数
        for(var i=0;i<first_day;i++){
            html+='<span class="g-calendar-grey">'+(last_date-(first_day-1)+i)+'</span>';
        }
        //本月的显示天数
        var postdate = new Date("Fri Mar 13 2015 10:04:54 GMT+0800"); 
        if (true && postdate.getFullYear() == year && postdate.getMonth() == month) { 
            html += '<span>1</span><span>2</span><span>3</span><span>4</span><span><a href="/2015/03/05/hibernate-note/" title="Hibernate笔记">5</a></span><span><a href="/2015/03/06/spring-note-2/" title="当天有2篇博客,第一篇:Spring笔记二">6</a></span><span>7</span><span>8</span><span>9</span><span>10</span><span>11</span><span>12</span><span><a href="/2015/03/13/jsp-servlet-note/" title="JSP/Servlet及相关技术笔记">13</a></span><span>14</span><span>15</span><span>16</span><span>17</span><span>18</span><span>19</span><span>20</span><span>21</span><span>22</span><span>23</span><span>24</span><span>25</span><span>26</span><span>27</span><span>28</span>';
        } else {
            for(var j=0;j<final_date;j++){        
                html+='<span id="d'+(j+1)+'">'+(j+1)+'</span>';
            }
        }
        //下个月的显示天数
        for(var k=0;k<surplus;k++){
            html+='<span class="g-calendar-grey">'+(k+1)+'</span>';
        }
        //fill
        this.oBody.innerHTML = html;
        // 当前状态
        if(year==this.c_year&&this.c_month==month){
            this.oBody.getElementsByTagName('span')[first_day+this.date-1].className='g-calendar-on';
        }

        // 对所有文章遍历,然后将有文章的日期加上链接,如果文章太多的话,生成页面会很大,去掉了
        
    },
    // next切换
    next:function(){
        var _that = this;
        this.oNext.onclick = function(){
            _that.month++;
            if(_that.month>11){
                _that.month = 0;
                _that.year++;
            }
            // 填充日历
            _that.fillDate(_that.year,_that.month);
        };
    },
    // back 切换
    back:function(){
        var _that = this;
        if(this.oBack != undefined) {
            this.oBack.onclick = function(){
                var postdate = new Date("Fri Mar 13 2015 10:04:54 GMT+0800"); 
                _that.year = postdate.getFullYear();
                _that.month = postdate.getMonth();
                // 填充日历
                _that.fillDate(_that.year,_that.month);
            };
        }
    },
    // now切换
    now:function(){
        var _that = this;
        if(this.oNow != undefined ) {
            this.oNow.onclick = function(){
                var nowDate = new Date(); 
                _that.year = nowDate.getFullYear();
                _that.month = nowDate.getMonth();
                // 填充日历
                _that.fillDate(_that.year,_that.month);
            };
        }
    },
    // prev切换
    prev:function(){
        var _that = this;
        this.oPrev.onclick = function(){
            _that.month--;
            if(_that.month<0){
                _that.month = 11;
                _that.year--;
            }
            // 填充日历
            _that.fillDate(_that.year,_that.month);
        };
    },
    init:function(){
        this.oTit.innerHTML = '<span>日</span><span>一</span><span>二</span><span>三</span><span>四</span><span>五</span><span>六</span>';
        // 获取今天的日历时间
        var now = new Date();
        this.c_year = this.year = now.getFullYear();
        this.c_month = this.month = now.getMonth();
        this.date = now.getDate();
        // 初始化--填充日历
        this.fillDate(this.year,this.month);
        //next切换
        this.next();
        //prev切换
        this.prev();
        //back 切换
        this.back();
        //now 切换
        this.now();
    }
}
new LGY_calendar('g-calendar');
</script>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2015/09/01/javascript-summary/">JavaScript 总结</a>
          </li>
        
          <li>
            <a href="/2015/08/28/javascript-oop-function-expression-and-async/">JavaScript 面向对象程序设计、函数表达式和异步编程</a>
          </li>
        
          <li>
            <a href="/2015/08/28/javascript-reference-type/">JavaScript 引用类型</a>
          </li>
        
          <li>
            <a href="/2015/08/28/javascript-grammar/">JavaScript 基本语法</a>
          </li>
        
          <li>
            <a href="/2015/08/10/java-web/">Java Web 笔记</a>
          </li>
        
      </ul>
    </div>
  </div>


  
    
<div class="widget-wrap">
  <h3 class="widget-title">Recent Comments</h3>
  <ul class="widget ds-recent-comments" data-num-items="5" data-show-avatars="0" data-show-title="1" data-show-time="1"></ul>
</div>
<!-- 需要多说的公用代码 -->


  

</aside>

        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2015 howiefh<br>
      Powered by <a href="http://zespia.tw/hexo/" target="_blank">Hexo</a> and Theme by <a href="https://github.com/howiefh/hexo-theme-landscape-f" target="_blank" title="Landscape-F">Landscape-F</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<!-- 多说公共JS代码 start (一个网页只需插入一次) -->

<script type="text/javascript">
  var duoshuoQuery = {short_name:"howiefh"};
  (function() {
	var ds = document.createElement('script');
	ds.type = 'text/javascript';ds.async = true;
	ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
	ds.charset = 'UTF-8';
	(document.getElementsByTagName('head')[0] 
		|| document.getElementsByTagName('body')[0]).appendChild(ds);
  })();
</script> 

<!-- 多说公共JS代码 end -->

<!-- 百度分享 start -->

<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":["mshare","douban","bdysc","sqq","qq","hi","baidu","huaban","youdao","sdo","mail","xg","diandian","fx","copy","print"],"bdPic":"","bdStyle":"1","bdSize":"16"},"share":{},"image":{"viewList":["qzone","tsina","tqq","renren","weixin"],"viewText":"分享到：","viewSize":"16"}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>

<!-- 百度分享 end -->

<!--
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="/js/jquery.min.js"></script>
-->
<script src="/js/jquery.min.js" type="text/javascript"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css" type="text/css">
  <script src="/fancybox/jquery.fancybox.pack.js" type="text/javascript"></script>


<div class="bottom-btn">

	<a class="icon-gotop" href="javascript:void(0)" title="返回顶部"></a>
	<script src="/js/gotop.js" type="text/javascript"></script>
	<!--
	<script src="/js/gotop.js"></script>
	-->


	<a class="icon-toc-toggle" href="javascript:void(0)" title="文章目录"></a>
	<!--
	<script src="/js/toc_aside_toggle.js"></script>
	-->

</div>
<script src="/js/toc_aside_toggle.js" type="text/javascript"></script>


<script src="/js/script.js" type="text/javascript"></script>

  </div>
</body>
</html>
